Hi all, im having a go at developing a simple app. i have little experience with Java and Android development. i have a little test app at the moment and have created a new class, im trying to create a new instance of this class on a button click. it fails to do so, i cant for the life of me see why so.. can someone shed any light on this?
Thanks
Debuging this shows it hitting the "LocationFactory locationf = new LocationFactory();" line and throwing an exception-
"java.lang.NullPointerException"
Main
Code:
package com.example.testapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private static final Context Context = null;
protected static final String TAG = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void mainButton(View view) throws IOException {
try {
LocationFactory locationf = new LocationFactory();
Toast.makeText(this, locationf.getAddress(),Toast.LENGTH_LONG).show();
} catch (Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Class
Code:
package com.example.testapp;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import java.io.IOException;
import java.util.Locale;
import java.util.List;
public class LocationFactory
{
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory()
{
}
public String getAddress() throws IOException
{
String ReturnAddress = "";
String Address = "", City = "", Country = "";
List<Address> addresses = null;
if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
// Use GPS Radio Location
Location GPSlocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Latitude = GPSlocation.getLatitude();
Longitude = GPSlocation.getLongitude();
}
else
{
// Use Cell Tower Location
Location NETlocation = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Latitude = NETlocation.getLatitude();
Longitude = NETlocation.getLongitude();
}
if(Latitude > 0 && Longitude > 0)
{
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
if(!addresses.isEmpty())
{
Address = addresses.get(0).getAddressLine(0);
City = addresses.get(0).getAddressLine(1);
Country = addresses.get(0).getAddressLine(2);
}
}
ReturnAddress = Address + " " + City + " " + Country;
return ReturnAddress;
}
}
I don't see anywhere in your code where you are calling the mainButton(View view) method. In the Android lifecycle, the onCreate method is the equivalent of a normal Java program's main() method, which means that code execution begins with the first line of onCreate(). Not knowing what you're trying to do, a good start would be to call your mainButton() method AFTER setContentView() in onCreate().
Side note: your mainButton() method has a View parameter that is never used. Is there a reason for that?
Android activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
e.g
Code:
Button button = (Button) findViewById(R.id.[B]button[/B]) // replace latter button with actual id defined in main xml.
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("[B]com.example.packagename.CLASSNAME[/B]")); // this should be your own package name.
}
});
Also define this in android manifest under the <application> and </application>
Code:
<activity
android:name=".[B]CLASSNAME[/B]"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="[B]com.example.packagename.CLASSNAME[/B]" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Change the values of BOLD text according to your own values.
I tried to help you as far as I understood your question. Please let me know if you face any problem I would be more than happy to help you. Rest I am also in the learning phase so you can always PM me if you face any problem.
Hit thanks if I have helped you in any way.
coolbud012 said:
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
Click to expand...
Click to collapse
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
jpepin said:
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
Click to expand...
Click to collapse
Oops yeah right read that now...I thought he want to start an activity... Anyways tried to delete my reply but not getting an option to delete.
There are many flaws in his code. And the other thing is if its his first app and if he has low level of programming experience then according to me it would be a next to impossible app for him, as per his code and what he is trying to implement.
I think he should rather start up with small apps, understand things and then move on to complex apps.
P.S - its just my opinion
Click to expand...
Click to collapse
Agreed that he should start small...which is exactly why your suggestion for creating and handling Intents makes no sense. Before that, he should first understand the activity lifecycle. Until then, he can just stick to trivial single-activity apps to gain experience.
OP: This code should be placed in the onCreate method:
Code:
Button button = (Button) findViewById(R.id.your_button_ID_here)
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
mainButton(); // get rid of the View parameter in this method...it's not needed
}
});
This will cause a new instance of your LocationFactory to be created, and will also cause your Toast message to be displayed.
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
osmorgan said:
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
Click to expand...
Click to collapse
I also believe in the same, I also keep on doing experiments and testing things out.
What I would suggest is that start with a small app and understand the insights on how android works and all...
Thanks
Potential Solution
Alright, I think I've found your problem. Have a look at where you define your variables in your LocationManager class:
Code:
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
This is your problem:
Code:
Context Context = null;
If your context is null, and you use it to create a geocoder and call Context.getSystemService, you'll hit a null pointer. You're trying to access an object (the Context) that doesn't even exist
I'd recommend you pass the context in the LocationManager constructor and then instantiate your objects there. That's standard java procedure.
Code:
private Context mContext = null;
Geocoder geocoder = null;
LocationManager manager = null;
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory(Context context)
{
this.mContext = context;
this.geocoder = new Geocoder(context, Locale.getDefault());
this.manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
}
I also renamed Context to mContext - it's generally a good idea to keep the instance's name separate from the class name.
Try that - it should work. Please feel free to ask any more questions - this is how I learned, and I think it's the best way!
I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Makbrar3215 said:
I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Click to expand...
Click to collapse
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Problem!
vijai2011 said:
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Click to expand...
Click to collapse
I did what you said. Yet I encountered a problem. Please see the attached screenshot.
When I hover over the X it says "Attribute name "public" associated with an element type "RadioButton" must be followed by the ' = '
character."
Where do I put the "="
Thanks by the way. You helped me out a lot!
you are mixing java with XML. Honestly, I suggest you start on a few beginner tutorials.
Just tell me what to do. I can't go through the guide. I need this app done by August 14.
Sent from my SGH-I337M using xda app-developers app
Bad Attitude to have. This isn't a "do my work for me" forum.
And like zalez was kind enough to point out, your putting java in xml. If you expect to make an app you need to read some beginner guides first.
you have almost a month to do it.
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Makbrar3215 said:
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Click to expand...
Click to collapse
http://developer.android.com/training/index.html
But you should probably start with generic Java 101 stuff
Set Switch status from incoming JSON data
Sorry to bump this thread after such a long time but I am facing a problem with switches myself and would appreciate some help. I have a JSON parser class which is retrieving data from a database. The retrieved info contains 'ID', 'name' and 'status' fields related to a device. I can display ID and name of each of the devices (there are several rows) using a listview but I don't know how to use the 'status' field value (it is either 1 or 0) to set an associated Switch component. I have to set the Switch associated with each listview item to ON if incoming 'status' value is 1 and set it OFF if 'status' is 0. I am lost on where to put the 'setChecked' method for every listview item. Here's the code of activity that shows these list items:
Code:
package com.iotautomationtech.androidapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ToggleButton;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
public class AllDevicesActivity extends ListActivity {
Switch mySwitch = (Switch) findViewById(R.id.switchButton);
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "external_link_removed";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "devices";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_devices);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditDeviceActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllDevicesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String status = c.getString(TAG_STATUS);
int toggleValue = Integer.parseInt(c.getString(TAG_STATUS));
boolean sBool = false;
if (toggleValue == 1) {
sBool = true;
}
if (status.equals("1")) {
status = "Status: ON";
}
else {
status = "Status: OFF";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewDeviceActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllDevicesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_STATUS},
new int[] { R.id.pid, R.id.name, R.id.status });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The XML file:
Code:
<RelativeLayout xmlns:android="schemas.android"
android:layout_width="fill_parent"
android:layout_height="65dip"
android:orientation="vertical"
android:layout_centerVertical="true"
>
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:textSize="17dip"
android:layout_below="@+id/name"
/>
<Switch
android:id="@+id/switchButton"
android:layout_alignParentRight="true"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginRight="6dip"
android:layout_centerVertical="true"
android:textOff="OFF"
android:textOn="ON"
android:onClick="onSwitchClicked"
/>
</RelativeLayout>
I have reached thus far with the code: [attached-image]
Now I only have to set those Switches according to status values from database. I have tried putting the setChecked in doInBackground method and onPostExecute method but it doesn't work. Do I have to save all status values in an array and start a loop to set all Switches? Where would that code go?
ANY kind of help/guidance here is appreciated!
I browsed around and haven't quite found a similar solution. I am fairly new to android dev and working with a few things for educational purposes. I've read up on fragments and activities but couldn't quite get it to work how I am trying to.
I have my list fragment, the list items are defined in the strings.xml as an array.
List Fragment (Con_70s.java):
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_main, container, false);
String[] items = getResources().getStringArray(R.array.con_70);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items));
return v;
}
The Strings (strings.xml):
Code:
<string-array name="con_70">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</string-array>
On the fragment I have an onListItemClick that currently tells me which position on the list I clicked (Con_70s.java):
Code:
@Override
public void onListItemClick(ListView l, View v, int position, long id){
Toast.makeText(getActivity(), "You selected " + position, Toast.LENGTH_LONG).show();
}
How would I modify this OnListItemClick to open a new fragment (or activity)? Let's say it would be called "New Activity".
startActivity(new Intent(this, NewActivity.class));
I guess you would like to send the position of the clicked item to the new activity. I suggest to use shared prefs
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
stock Recovery
Masrepus said:
startActivity(new Intent(this, NewActivity.class));
I guess you would like to send the position of the clicked item to the new activity. I suggest to use shared prefs
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
stock Recovery
Click to expand...
Click to collapse
Or you could just use setArguaments(); to put the information in a Bundle then use getArguaments(); from the new activity to retrieve it? Same with fragments.
how does it know which item I picked to associate with each fragment? by using position?
can you give an example?
nevermind, thats declared with
Code:
onListItemClick(ListView l, View v, int position, long id){
Data Transferring Tool for All Android Powered Devices
Data transmission, digital transmission, or digital communications is the physical transfer of data (a digital bit stream or a digitized analog signal) over a point-to-point or point-to-multipoint communication channel. Examples of such channels are copper wires, optical fibers, wireless communication channels, storage media and computer buses. The data are represented as an electromagnetic signal, such as an electrical voltage, radiowave, microwave, or infrared signal. READ MORE
Click to expand...
Click to collapse
There are several ways to transfer data between different type of devices. For Example, from SmartPhones to Another SmartDevices By Bluetooth that devices should connect together. Your App should handle these Processes. Beside using sensors to transfer data between devices there is In-App feature that allows Send/Receive data inside app. For Example Send Data from App on SmartPhone to client side on SmartWatch. In this way the application use system connection and it will handle data and not processes of detecting & connecting to peer(s).
In this thread I will write several Programming Tutorials for Data Transferring in Android.
Then I will use these tutorials to create a Tool for Send/Receive all types of Data to All Android Powered Devices.
android Auto | Tutorial
android Wear | Watch-To-Phone Tutorial | Phone-To-Watch Tutorial
android TV | Tutorial
Server Download/Upload | Tutorial
Bluetooth | Tutorial
NFC | Tutorial
Wifi Direct| Tutorial
I will use Source Code of Current Geeks Empire Open Source Projects as example.
If you want to Contribute in this Project (Tutorials/Tool) Send Message Or Email.
Click to expand...
Click to collapse
Don't Forget to Hit Thanks
XDA:DevDB Information
Data Transferring, Tool/Utility for all devices (see above for details)
Contributors
Geeks Empire
Source Code: https://play.google.com/store/apps/dev?id=6231624576518993324
Version Information
Status: Testing
Created 2015-08-19
Last Updated 2016-11-16
Android Auto [Data Transferring]
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Android Auto is a smartphone projection standard developed by Google to allow mobile devices running the Android operating system (version 5.0 "Lollipop" and later) to be operated in automobiles through the dashboard's head unit. Android Auto was announced on June 25, 2014, at Google I/O 2014. The Android Auto mobile app was released on March 19, 2015. READ MORE
Click to expand...
Click to collapse
Android Auto was designed with safety in mind. With a simple and intuitive interface, integrated steering wheel controls, and powerful new voice actions, it's designed to minimize distraction so you can stay focused on the road. READ MORE
Click to expand...
Click to collapse
NOTE: Currently Only Media Player & Short Messaging App allowed on Google Play Store for Android Auto Distribution.
But Soon there will be another category for more Hands-Free App on Android Auto.
Android Auto is now available on these cars
Hyundai Sonata (May 2015) Take it to Service Center & Ask for Upgrade to Android Auto
Skoda Fabia (June 2015)
Skoda Superb (June 2015)
Skoda Octavia (June 2015)
Honda Accord (August 2015)
VW Golf/GTI (September 2015)
Chevrolet Cruze (2016)
& Enabled Hardware are
GPS and high-quality GPS antennas
Steering-wheel controls
Sound system
Directional speakers
Directional microphones
Wheel speed
Compass
Mobile antennas
### Let Start Coding ###
What you need is ability to create Hello World! project
Click to expand...
Click to collapse
You will learn How To Use
BroadcastReceiver, Custom Intent-Filet, Send/Receive Text to AndroidAuto,
Notification & CarExtender-Notification & etc.
Click to expand...
Click to collapse
. from Bottom to Top
First you need to Add XML file as meta-data for AndroidManifest to declare app as AndroidAuto Enabled app for system.
Under the .../res/ create xml folder. inside xml folder create xml resource file: automotive_app_desc.xml and Paste this
Code:
<?xml version="1.0" encoding="utf-8"?>
<automotiveApp>
<uses name="[B]notification[/B]"/>
<!-- [I]notification attribute shows your app is messaging app that only create androidAuto compatible notification[/I] -->
</automotiveApp>
then you need to link this file into manifest under <application />
Code:
<meta-data
android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" /
>
After Installing App, It will notify Android Auto System.
There is 2 parts important for AndroidAuto Notification When TTS read content & when want to Reply Or send reply.
So to handle these parts we should define two BroadcastReceiver in manifest & creating classes.
Code:
<receiver android:name=".[B]MessageReadReceiver[/B]">
<intent-filter>
<action android:name="net.test.cartest.[B]ACTION_MESSAGE_READ[/B]"/>
</intent-filter>
</receiver>
<receiver android:name=".[B]ReplyReceiver[/B]" >
<intent-filter>
<action android:name="net.test.cartest.[B]ACTION_MESSAGE_REPLY[/B]" />
</intent-filter>
</receiver>
Then Create Classes & setup both of them as extends BroadcastReceiver.
Inside Activity class we need to create Android-Auto Compatible Notification.
For Messaging App It should be after users receive new message. I used it for Translator App > geTranslate. It means Notification will show translated text on Car Monitor Read result & use Reply action to reuse translator. However Translator App is not allowed for Android Auto.
Before creating notification we should define Intent Action to invoke BroadcastReceiver previously defined.
Code:
private Intent getMessageReadIntent(int conversationId) {
return new Intent().setAction(READ_ACTION).putExtra(CONVERSATION_ID, id); //[FONT=Impact](Check Source Code)[/FONT]
}
//Conversation ID must be unique.
private Intent getMessageReplyIntent(int conversationId) {
return new Intent().setAction(REPLY_ACTION).putExtra(CONVERSATION_ID, conversationId); //[FONT=Impact](Check Source Code)[/FONT]
}
Creating Notification itself is similar to phone notification But we need to extend it for Cars. to do this we need another component UnreadConversation.Builder
Code:
//This element will handle new how create new notifications
UnreadConversation.Builder unreadConversationBuilder = new UnreadConversation.Builder(sender)
.setLatestTimestamp(timestamp)
.setReadPendingIntent(readPendingIntent)
.setReplyAction(replyIntent, remoteInput);
unreadConversationBuilder.addMessage(message);
Then we should use it for CarExtender()
Code:
new CarExtender().setUnreadConversation(unreadConversationBuilder.build();
Here is Complete Function to define and create Android Auto Compatible Notification
Code:
private void sendNotificationToCar(int conversationId, String sender, String message, long timestamp) {
PendingIntent readPendingIntent = PendingIntent.getBroadcast(
getApplicationContext(),
conversationId,
getMessageReadIntent(conversationId),
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
.setLabel("Remote Inpute").build();
PendingIntent replyIntent = PendingIntent.getBroadcast(
getApplicationContext(),
conversationId,
getMessageReplyIntent(conversationId),
PendingIntent.FLAG_UPDATE_CURRENT);
UnreadConversation.Builder unreadConversationBuilder = new UnreadConversation.Builder(sender)
.setLatestTimestamp(timestamp)
.setReadPendingIntent(readPendingIntent)
.setReplyAction(replyIntent, remoteInput);
unreadConversationBuilder.addMessage(message);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ic_launcher))
.setContentText(message)
.setWhen(timestamp)
.setContentTitle(sender)
.setContentIntent(readPendingIntent)
.extend(new CarExtender().setUnreadConversation(unreadConversationBuilder.build()))
.setColor(Color.RED);
NotificationManagerCompat.from(this).notify(conversationId, builder.build());
}
Now you should handle Receivers. inside MessageReadReceiver you need to define actions to occur after TTS Engine read the content of notification & inside ReplyReceiver How reply actions work, in geTranslate I setup ReplayReceiver to invoke translator to translate what user spoke through car microphone.
Code:
public class [B]ReplyReceiver [/B]extends BroadcastReceiver { //[FONT=Impact](Check Source Code)[/FONT]
@Override
public void onReceive(Context context, Intent intent) {
if (MainActivity.REPLY_ACTION.equals(intent.getAction())) {
CharSequence reply = getMessageText(intent);
//Do What you want...
}
}
private CharSequence getMessageText(Intent intent) {
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
return remoteInput.getCharSequence(MainActivity.EXTRA_VOICE_REPLY);
}
return null;
}
}
Up to Here you did what necessary for your app to support Android Auto. If you have access to real AndroidAuto Powered Vehicle Just Install you app and connect it to car & test your application.
But If you don't have access to androidAuto car you need to use simulator.
Code:
Install [COLOR=RoyalBlue][URL="http://forum.xda-developers.com/attachment.php?attachmentid=3444494&stc=1&d=1439998349"][B]CarNotification.APK[/B][/URL][/COLOR]
Code:
Install [B][URL="http://forum.xda-developers.com/attachment.php?attachmentid=3444491&stc=1&d=1439998135"]Simulator APK[/URL][/B] & Go to Setting > Notification Access > Enable Simulator
HOW TO Test Sample
Code:
[B]Open [/B]CarTest [B]Click [/B]on Text Then Click [B]Home [/B]& [B]Run Simulator [/B]> Wait [B]15Seconds [/B]to See Notification
If you find any mistake Or issue in my codes Please inform me.
Click to expand...
Click to collapse
Don't forget to Hit Thanks
Android Wear [Watch-To-Phone][Data Transferring]
Android Wear is a version of Google's Android operating system designed for smartwatches and other wearables.
By pairing with mobile phones running Android version 4.3+, Android Wear integrates Google Now technology and mobile notifications into a smartwatch form factor. It also adds the ability to download applications from the Google Play Store.
Android Wear supports both Bluetooth and Wi-Fi connectivity, as well as a range of features and applications. Watch face styles include round, square and rectangular. Released devices include Motorola Moto 360,the LG G Watch, and the Samsung Gear Live.Hardware manufacturing partners include ASUS, Broadcom, Fossil, HTC, Intel, LG, MediaTek, Imagination Technologies, Motorola, Qualcomm, and Samsung.
In the first six months of availability, Canalys estimates that over 720,000 Android Wear smartwatches were shipped.As of 15 May 2015, Android Wear had between one and five million application installations.
Click to expand...
Click to collapse
### Let Start Coding ###There is just few different between AndroidApp on Phones & AndroidApp on Wearable.
The most important part is Optimizing User-Interface for AndroidWear & then keep in mind which API not available on AndroidWear. These APIs are not available on AndroidWear
android.webkit
android.print
android.app.backup
android.appwidget
android.hardware.usb
NOTE: Do Not set all processes of your app on SmartWatch Module. Cause there is smaller Battery, Memory& weaker Processor.
NOTE: You should use Android Studio to create AndroidWear App.
(However there is tricky way to use eclipse for androidWear But It s better to migrate to AndroidStudio ASAP.)
. from Bottom to Top /Watch Client
When you want to create New Android Application you can choose AndroidWear App Module then AndroidStudio will add necessary AndroidWear Components and Gradle Config automatically.
But you can add AndroidWear Module manually in your current project.
Code:
Go to
File > New > New Module > Select AndroidWear & Next to Finish.
Then you need to add required configuration in your Host Application to Link AndroidWear Module.
Open build.gradle (Module: name-of-project) of Host Application. & Add wearProject to Dependencies
Code:
dependencies{
...
wearApp project{':NAME-OF-PROJECT'}
...
}
Then Save & Sync.
Open AndroidManifest.xml & Add Uses-Features & Uses-Permissions
Code:
<uses-feature android:name="android.hardware.type.watch" />
NOTE: If you want to set new permission that is not in Phone Module you have to set on both Phone & Watch AndroidManifest. (Check Source Code)
There other components are same But for app that want to communicate between Phone & Watch add this meta-data under Application tag
Code:
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
There is different between phone layout design & watch. There is 3 layout.xml files for each Activity on SmartWatch.
main.xml Just Hold the View >>
<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.WatchViewStub
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/watch_view_stub"
android:layout_width="match_parent" android:layout_height="match_parent"
app:rectLayout="@layout/rectangle_main"
app:roundLayout="@layout/round_main"
tools:context=".WearActivity" tools:deviceIds="wear"></android.support.wearable.view.WatchViewStub>
Click to expand...
Click to collapse
rectangle_main.xml for Rectangle SmartWatch Display that All GUI components must Add here
round_main.xml for Round SmartWatch Display that All GUI components must Add here
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
[B] tools:context=".MainWear"[/B]
android:background="@android:color/white"
[B]tools:deviceIds="wear_square" [/B]>
[B]<!--
You should set context for activity that handle the components and Id to call on main view.
+
All other components like Buttons, TextViews, EditTextx should call here.
-->[/B]
</RelativeLayout>
Now I should add functionality to GUI components in Java.Classes.
To Communicate with Phone First of all I should Initiate GoogleApiClient to Get Node (Phone) connected to watch & get it ready for data communication
Code:
GoogleApiClient client = new GoogleApiClient.Builder(context).addApi(Wearable.API).build();
new Thread(new Runnable() {
@Override
public void run() {
client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
NodeApi.GetConnectedNodesResult result = Wearable.NodeApi.getConnectedNodes(client).await();
List<Node> nodes = result.getNodes();
if (nodes.size() > 0) {
nodeId = nodes.get(0).getId();
}
client.disconnect();
}
}).start();
Then I should define WatchViewStub Listener & then other components inside it
Code:
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
//Here I should add all other functionalities
}
});
The proper Input Method on Android Wear is Voice Input. The main reason for this is small screens.
To Launch Voice Recognition Engine Call This Method
Code:
private static final int SPEECH_REQUEST_CODE = 0;
private void displaySpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, SPEECH_REQUEST_CODE);
}
After This I need to get result from engine so i should define onActivityResult
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) {
//Here I should Handle Results
List<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
final String speech = results.get(0).toString();[B]
[COLOR=Red]//Here you can send this data to phone[/COLOR][/B]
}
To send data to app client on phone you can use Wearable.MessageApi.sendMessage()
Code:
if (nodeId != null) {
new Thread(new Runnable() {
@Override
public void run() {
client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
Wearable.MessageApi.sendMessage(client, nodeId, MESSAGE, null);
client.disconnect();
}
}).start();
}
. from Bottom to Top /Phone Client
On the Phone Side Open AndroidManifest.xml & Add Service to Handle Received data from Watch with specific <intent-filter/>
<service android:name=".WearReceiver" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
Then Create Class extends of WearableListenerService to get data and add all operation we want.
Code:
public class WearReceiver extends WearableListenerService {
@Override
public void onMessageReceived(MessageEvent messageEvent) {
String getWear = messageEvent.getPath(); [COLOR=Red][B]//Text from Watch[/B][/COLOR]
System.out.println("DEVICE >> " + messageEvent.getPath());
}
}
Done! But You Always you need to Test your App.
If you create Signed APK you can Install it on Phone & It will install on AndroidWear automatically.
NOTE: buildToolsVersion must be same on both Phone & Watch Module.
If you have AndroidWear Device Just Connect it & install it like normal app on phones. It same if you run Emulator But to use emulator you need to do few steps before
First go to Android Virtual Device (AVD) Manager & Create Emulator for both Square & Round Display Watches.
Install AndroidWear App from Google Play Store
In AndroidWear App select Emulator
Open Terminal & Go to ADB directory & type this command
Code:
adb -d forward tcp:5601 tcp:5601
On AndroidWear App Select Connect Emulator
Here is 2 Open Source Projects of Geeks Empire to Help you better for tutorial.
geTranslate
APK + Source Code 1-2-3 (Full) | G Drive
Keep Note
APK + Source Code (Full)
If you find any mistake Or issue in my codes Please inform me.
Click to expand...
Click to collapse
Don't forget to Hit Thanks
Android Wear [Phone-To-Watch][Data Transferring]
Android Wear is a version of Google's Android operating system designed for smartwatches and other wearables.
By pairing with mobile phones running Android version 4.3+, Android Wear integrates Google Now technology and mobile notifications into a smartwatch form factor. It also adds the ability to download applications from the Google Play Store.
Android Wear supports both Bluetooth and Wi-Fi connectivity, as well as a range of features and applications. Watch face styles include round, square and rectangular. Released devices include Motorola Moto 360,the LG G Watch, and the Samsung Gear Live.Hardware manufacturing partners include ASUS, Broadcom, Fossil, HTC, Intel, LG, MediaTek, Imagination Technologies, Motorola, Qualcomm, and Samsung.
In the first six months of availability, Canalys estimates that over 720,000 Android Wear smartwatches were shipped.As of 15 May 2015, Android Wear had between one and five million application installations.
Click to expand...
Click to collapse
### Let Start Coding ###
There is just few different between AndroidApp on Phones & AndroidApp on Wearable.
The most important part is Optimizing User-Interface for AndroidWear & then keep in mind which API not available on AndroidWear. These APIs are not available on AndroidWear
android.webkit
android.print
android.app.backup
android.appwidget
android.hardware.usb
NOTE: Do Not set all processes of your app on SmartWatch Module. Cause there is smaller Battery, Memory& weaker Processor.
NOTE: You should use Android Studio to create AndroidWear App.
(However there is tricky way to use eclipse for androidWear But It s better to migrate to AndroidStudio ASAP.)
WHY Should You Transfer Data to AndroidWear Client?
- Beside using Wear Notification Extender to deliver info to SmartWatch you can transfer data to Watch Client of your App directly. In this way you will be able to do some modification on data before displaying to users on watches OR sharing data securely inside your app.
from Bottom to Top /Watch Client
When you want to create New Android Application you can choose AndroidWear App Module then AndroidStudio will add necessary AndroidWear Components and Gradle Config automatically.
But you can add AndroidWear Module manually in your current project.
Code:
Go to
File > New > New Module > Select AndroidWear & Next to Finish.
Then you need to add required configuration in your Host Application to Link AndroidWear Module.
Open build.gradle (Module: name-of-project) of Host Application. & Add wearProject to Dependencies
Code:
dependencies{
...
wearApp project{':NAME-OF-PROJECT'}
...
}
Then Save & Sync.
Open AndroidManifest.xml & Add Uses-Features & Uses-Permissions
Code:
<uses-feature android:name="android.hardware.type.watch" />
NOTE: If you want to set new permission that is not in Phone Module you have to set on both Phone & Watch AndroidManifest. (Check Source Code)
There other components are same But for app that want to communicate between Phone & Watch add this meta-data under Application tag
Code:
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
***AndroidWear GUI Guide
There is different between phone layout design & watch. There is 3 layout.xml files for each Activity on SmartWatch.
main.xml Just Hold the View >>
Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.WatchViewStub
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/watch_view_stub"
android:layout_width="match_parent" android:layout_height="match_parent"
app:rectLayout="@layout/rectangle_main"
app:roundLayout="@layout/round_main"
tools:context=".WearActivity" tools:deviceIds="wear"></android.support.wearable.view.WatchViewStub>
rectangle_main.xml for Rectangle SmartWatch Display that All GUI components must Add here
round_main.xml for Round SmartWatch Display that All GUI components must Add here
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainWear"
android:background="@android:color/white"
tools:deviceIds="wear_square" >
<!--
You should set context for activity that handle the components and Id to call on main view.
+
All other components like Buttons, TextViews, EditTextx should call here.
-->
</RelativeLayout>
You should set context for activity that handle the components and Id to call on main view.
+
All other components like Buttons, TextViews, EditTextx should call here.
***
I should define an Activity & Service extends WearableListenerService for Wear Module.
The Service must have intent filter to Bind it.
Code:
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
Inside the listener you can handle the Received Data But in this example I just get the Intent-Filter-Action & launch the activity by getting the data path
Code:
if(messageEvent.getPath().equalsIgnoreCase("String Intent Filter Action")){
//Start Activity
}
In this example I used simple text as data so to get text data I can setup data like this
Code:
@Override
public void onMessageReceived(MessageEvent messageEvent) {
String receivedTextFromPhoneClient = messageEvent.getData().toString();
}
In case you want to launch an activity you have to setup some implementation to receive data
Code:
public class MainActivity extends Activity implements MessageApi.MessageListener, GoogleApiClient.ConnectionCallbacks{}
& put all necessary override functions
Code:
public void onMessageReceived( final MessageEvent messageEvent ) {}
public void onConnected(Bundle bundle) {}
public void onConnectionSuspended(int i) {}
Inside activity I must initialize the GoogleApiClient to connect to peer and get data
Code:
GoogleApiClient mApiClient = new GoogleApiClient.Builder( this )
.addApi( Wearable.API )
.addConnectionCallbacks( this )
.build();
if( mApiClient != null && !( mApiClient.isConnected() || mApiClient.isConnecting() ) )
mApiClient.connect();
Make Sure to release Listener when quitting the activity
Code:
@Override
protected void onStop() {
if ( mApiClient != null ) {
Wearable.MessageApi.removeListener( mApiClient, this );
if ( mApiClient.isConnected() ) {
mApiClient.disconnect();
}
}
super.onStop();
}
To get Received Data from peer you should do it inside onMessageReceived function //(Check Source Code)
Code:
@Override
public void onMessageReceived( final MessageEvent messageEvent ) {
runOnUiThread( new Runnable() {
@Override
public void run() {
if( messageEvent.getPath().equalsIgnoreCase( WEAR_MESSAGE_PATH ) ) {
mAdapter.add(new String([B]messageEvent.getData()[/B])); //Data from Phone
mAdapter.notifyDataSetChanged();
}
}
});
}
But Where is Data come from?
Let Code the Phone Client to Send Data to SmartWatch.
from Bottom to Top /Phone Client
First of All Don't forget to add <meta-data/> to AndroidManifest.xml under <Application/>
Inside Activity Setup Views as you prefer to get user input & send it to watch.
In this example I set EditText & Button to get input and send data.
Like Watch Client First initialize GoogleApiClient so that I need to add implementation to GoogleApiClient.ConnectionCallbacks & its override functions.
Just Call these three functions at onCreate session.
Code:
private void initGoogleApiClient() {
mApiClient = new GoogleApiClient.Builder( this )
.addApi( Wearable.API )
.build();
mApiClient.connect();
}
Code:
private void init() {
mSendButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = mEditText.getText().toString();
if (!TextUtils.isEmpty(text)) {
sendMessage(WEAR_MESSAGE_PATH, text);
}
}
});
}
& final Send function to Watch Client
Code:
private void [COLOR=Red][B]sendMessage[/B][/COLOR]( final String path, final String text ) {
new Thread( new Runnable() {
@Override
public void run() {
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( mApiClient ).await();
for(Node node : nodes.getNodes()) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
mApiClient, node.getId(), path, text.getBytes() ).await();
}
runOnUiThread( new Runnable() {
@Override
public void run() {
mEditText.setText( "" );
}
});
}
}).start();
}
NOTE: There is two parameters that the values & names must be same inside both Phone & Watch Client
The String of Intent-Filter-Action & Message-Path
Code:
private static final String ACTION = "/start_activity";
private static final String WEAR_MESSAGE_PATH = "/message";
NOTE: buildToolsVersion must be same on both Phone & Watch Module.
If you have AndroidWear Device Just Connect it & install it like normal app on phones. It same if you run Emulator But to use emulator you need to do few steps before
First go to Android Virtual Device (AVD) Manager & Create Emulator for both Square & Round Display Watches.
Install AndroidWear App from Google Play Store
In AndroidWear App select Emulator
Open Terminal & Go to ADB directory & type this command
Code:
adb -d forward tcp:5601 tcp:5601
On AndroidWear App Select Connect Emulator
Here is 2 Open Source Projects of Geeks Empire to Help you better for tutorial.
geTranslate
APK + Source Code 1-2-3 (Full)
Keep Note
[URL="http://forum.xda-developers.com/attachment.php?attachmentid=3427464&d=1438637814"]APK + Source Code (Full)[/URL]
NOTE:
If you find any mistake Or issue in my codes Please inform me.
Click to expand...
Click to collapse
Don't forget to Hit Thanks
Android TV [Data Transferring]
Android offers a rich user experience that's optimized for apps running on large screen devices, such as high-definition televisions. Apps on TV offer new opportunities to delight your users from the comfort of their couch...
Android TV apps use the same structure as those for phones and tablets. This similarity means you can modify your existing apps to also run on TV devices or create new apps based on what you already know about building apps for Android.
Click to expand...
Click to collapse
### Let Start Coding ###For TV Apps you must just Focus on GUI. You can use all your codes for Phone App but for Bigger Layout Components.
Also There might be some limitation for Hardware on TV.
This is list of Un-Supported Hardware feature on Android TV
Code:
Touchscreen - android.hardware.touchscreen
Touchscreen emulator - android.hardware.faketouch
Telephony - android.hardware.telephony
Camera - android.hardware.camera
Near Field Communications (NFC) - android.hardware.nfc
GPS - android.hardware.location.gps
Microphone - android.hardware.microphone
Sensors - android.hardware.sensor
. from Bottom to Top
In AndroidManifest.xml you must declare <activity /> for TV class with different Category for Intent Filter & Theme.
Code:
<activity
android:name="com.example.android.TvActivity"
android:label="@string/app_name"
android:theme="@style/[COLOR=Red][B]Theme.Leanback[/B][/COLOR]">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="[COLOR=Red][B]android.intent.category.LEANBACK_LAUNCHER[/B][/COLOR]" />
</intent-filter>
</activity>
& Under <manifest/> declare TV Support Library usage.
Code:
<uses-feature android:name="android.software.leanback"
android:required="false" />
Before/After this declaration you need to configue Hardware feature requirement. For Example:
Code:
...
<uses-feature android:name="android.hardware.touchscreen"
android:required="false" />
...
Also When you want to Add TV support you should design new graphical element as banner for LeanBackLauncher
Under <application /> add
Code:
...
android:banner="@drawable/banner"
...
After this Focus on GUI & Test App. You need to define bigger graphical component that user can see from longer distance compare when look at phone or tablet.
GUI Guide for Android TV App
NOTE: Creating TV Module Using Android Studio Will Add Everything you need for TV App automatically.
If you find any mistake Or issue in my codes Please inform me.
Click to expand...
Click to collapse
Don't forget to Hit Thanks
Server [Upload | Download][Data Transferring]
HOW TO Create Cloud Base App Using Google Cloud
HOW TO Create Cloud Base App Using Custom Server (Coming Soon)
Bluetooth [Data Transferring]
The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.
Using the Bluetooth APIs, an Android application can perform the following:
Scan for other Bluetooth devices
Query the local Bluetooth adapter for paired Bluetooth devices
Establish RFCOMM channels
Connect to other devices through service discovery
Transfer data to and from other devices
Manage multiple connections
Click to expand...
Click to collapse
Using Bluetooth can be so Helpful in many cases.
Send to & Receive Data from many devices. SmartPhone,any Bluetooth stations & etc.
But If you want to have control of what happen with data sharing with Bluetooth you must learn How to Transfer Data through Bluetooth Socket. For many simple cases Android Provided Intent base Bluetooth Sharing But It is not enough. So I will write here how to use Bluetooth for both situation.
### Let Start Coding ###
Additionally in this tutorial you will learn How to access Files & Converting to byteArray.
. from Bottom to Top /Watch Client
Start New Project & Leave everything to default.
After Sync Gradle Open AndroidManifest.xml to Add Permissions.
Code:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> //to Enable/Disable Bluetooth
<uses-permission android:name="android.permission.BLUETOOTH"/>
Also for Android API 23+ you should ask for Runtime Permission too.
Code:
if(Build.VERSION.SDK_INT >= 23) {
String[] Permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN};
requestPermissions(Permissions, 10296);
}
Then Open your Bluetooth Activity and Add this Code.
Here is Simple Way to Share File using Bluetooth. Like other Intent sharing Just Invoke its intent-filter
Code:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");//define type
File f = new File(Environment.getExternalStorageDirectory(), "DIR_TO_FILE");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(intent);
Little More Complex Way is to use Bluetooth Socket.
It finds List of All Paired Bluetooth Devices.
Code:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
System.out.println(device.getName() + "\n" + device.getAddress() + "\n\n");
}
}
to connect to another device you need to have its MacAddress.
Code:
String macAddress = new BluetoothDevice().getAddress();
BluetoothDevice [COLOR=Red][B]device [/B][/COLOR]= mBluetoothAdapter.getRemoteDevice(macAddress);
After this you should invoke instance of Socket to start Connection.
NOTE: Nothing should define on Main View. In other hand you have to use Thread(); for background Process.
Code:
Connecting [B]connectThread [/B]= new Connecting([COLOR=Red][B]device [/B][/COLOR]/*Pass Device Information to Thread()*/);
[B]connectThread[/B].start();
Code:
private class Connecting extends Thread {
private final BluetoothSocket [COLOR=Red]bluetoothSocket [/COLOR];
private final BluetoothDevice bluetoothDevice ;
private String mSocketType;
public ConnectThread(BluetoothDevice device) {
bluetoothDevice = device;
[B]BluetoothSocket [/B][COLOR=Red]tmp [/COLOR]= null;
try {
[COLOR=Red]tmp [/COLOR]= device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
catch (IOException e) {e.printStackTrace();}
[COLOR=Red]bluetoothSocket [/COLOR]= tmp;
}
public void run() {
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
try {
[COLOR=Red][B]bluetoothSocket.connect();[/B][/COLOR]
} catch (IOException e) {
try {
[COLOR=Red]bluetoothSocket[/COLOR].close();
} catch (IOException e2) {e2.printStackTrace();break;}
return;
}
[COLOR=RoyalBlue][B]//Handle Actions After Connecting.
//Ask to Write & Read Socket Data
// SO HERE you should start another Thread(); to handle [COLOR=Red]Write/Read[/COLOR] Process
[/B][/COLOR][COLOR=RoyalBlue][B][COLOR=Red][COLOR=SeaGreen]globalConnectedThread [/COLOR]= new ConnectedThread(socket, socketType).start();[/COLOR][/B][/COLOR][COLOR=RoyalBlue][COLOR=Black]//pass the socket Information[/COLOR][/COLOR]}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {e.printStackTrace();}
}
}
So Check this snippet Carefully and Read Comments
Code:
private class ConnectedThread extends Thread {
private final BluetoothSocket [B]mmSocket[/B];
private final InputStream [COLOR=Red][B]mmInStream[/B][/COLOR];
private final OutputStream [COLOR=Red][B]mmOutStream[/B][/COLOR];
public ConnectedThread(BluetoothSocket socket, String socketType) {
[B]mmSocket [/B]= socket;[COLOR=Red] //you call it on Connecting thread after successful connecting process So pass the socket to this thread[/COLOR]
InputStream [B]tmpIn [/B]= null;
OutputStream [B]tmpOut [/B]= null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = [B]socket[/B].getInputStream();
tmpOut = [B]socket[/B].getOutputStream();
} catch (IOException e) {}
[COLOR=Red][B]mmInStream [/B][/COLOR]= tmpIn;
[COLOR=Red][B]mmOutStream [/B][/COLOR]= tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (/*define indicator to check if sockets are connected you can do it by using a integer or boolean var*/) {
try {
// Read from the InputStream in loop until connection not lost
bytes = [B]mmInStream[/B].[B][COLOR=Red]read([COLOR=Black]buffer[/COLOR])[/COLOR][/B];
// Send the obtained bytes to the UI Activity OR SAVE Data
//so we call a function save data to file.
saveFile("name_of_file");
//pass read data to views
} catch (IOException e) {
// Start the service over to restart listening mode
this.start();
break;
}
}
}
public void [B]write[/B](byte[] buffer) {//next snippet will show how to use it.
try {
[B]mmOutStream[/B].[COLOR=Red][B]write([COLOR=Black]buffer[/COLOR])[/B][/COLOR];
// Share the sent message back to the UI Activity
} catch (IOException e) {}
}
public void cancel() {
try {
[B]mmSocket[/B].close();
} catch (IOException e) {}
}
}
To Write to Socket from File you must read content of File (that is why we got permission for reading sdcard) and convert it to array of byte and pass to socket. So define ConnectedThread and call write(byte[]) function
Code:
ConnectedThread connectedThread = [COLOR=SeaGreen][B]globalConnectedThread[/B][/COLOR];//this is the value defined after socket connected.
byte[] sendData = [B]readFile[/B]("file_name_on_sdcard").getBytes();//Check out next snippet for readFile Function
[B]connectedThread.[COLOR=Red]write[/COLOR](sendData);[/B]
This Function to read simple text file from sdcard
Code:
public String [B]readFile[/B](String fileName){
String temp = "";
File G = new File(Environment.getExternalStorageDirectory(), fileName);
if(!G.exists()){
System.out.println(fileName + " NOT FOUND");
}
else{
try{
BufferedReader br = new BufferedReader(new FileReader(G));
int c;
temp = "";
while((c = br.read()) != -1){
temp = temp + Character.toString((char)c);
}
}
catch(Exception e){e.printStackTrace();}
}
return temp;//content of file
}
In other hand you must Handle read data on socket and save it.
Code:
public void [B]saveFile[/B](String fileName, String content){
File G = new File(Environment.getExternalStorageDirectory(), fileName);
try {
FileOutputStream fOut = new FileOutputStream(G);
fOut.write((content).getBytes());
fOut.flush();
fOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
NOTE: As you may realized this tutorial contained functionality for both Client & Server Side of Bluetooth connection.
So when compiled your test app, install it on 2 devices & pair them.
Download SourceCode & Enjoy
If you find any mistake Or issue in my codes Please inform me
Click to expand...
Click to collapse
Don't forget to Hit Thanks
WiFi Direct | Android Beam [Client|Server][Data Transferring]
Wi-Fi peer-to-peer (P2P) allows Android 4.0 (API level 14) or later devices with the appropriate hardware to connect directly to each other via Wi-Fi without an intermediate access point (Android's Wi-Fi P2P framework complies with the Wi-Fi Alliance's Wi-Fi Direct™ certification program). Using these APIs, you can discover and connect to other devices when each device supports Wi-Fi P2P, then communicate over a speedy connection across distances much longer than a Bluetooth connection. This is useful for applications that share data among users, such as a multiplayer game or a photo sharing application.
The Wi-Fi P2P APIs consist of the following main parts:
Methods that allow you to discover, request, and connect to peers are defined in the WifiP2pManager class.
Listeners that allow you to be notified of the success or failure of WifiP2pManager method calls. When calling WifiP2pManager methods, each method can receive a specific listener passed in as a parameter.
Intents that notify you of specific events detected by the Wi-Fi P2P framework, such as a dropped connection or a newly discovered peer.
You often use these three main components of the APIs together. For example, you can provide a WifiP2pManager.ActionListener to a call to discoverPeers(), so that you can be notified with the ActionListener.onSuccess() and ActionListener.onFailure() methods. A WIFI_P2P_PEERS_CHANGED_ACTION intent is also broadcast if the discoverPeers() method discovers that the peers list has changed.
Click to expand...
Click to collapse
WiFi Direct can be used as main part of data transferring Or you can use it after initial connection with NFC. Android System uses Wifi Direct & Bluetooth to transfer a large amount of data after NFC connection.
### Let Start Coding ###
Wifi Direct has 2 part: Client & Server.
Your app must have contains both parts to be able to transfer data via Wifi Direct.
Both sides need 3 classes: Activity - BroadcastReceiver - Server.
Client Side needs more work to do, so I begin with Wifi Direct - Client
Click to expand...
Click to collapse
Note: Developing for Socket Communication needs vivid vision to understand how it works. Then use all components correctly step by step. So I will explain more about each section. Read Carefully.
. Wifi Direct | Client
Create a Project on Android Studio. Set minSdk to API 14 & Open AndroidManifest.xml to add required permissions and features
Code:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I don't enter to layout.xml & won't talk about GUI/UX in this tutorial. So you can design your layout and put codes and expanding functionality of your apps.
Click to expand...
Click to collapse
So create 3 classes & register them to Manifest.
ClientActivity
ClientReceiver
ClientService
Open ClientActivity. First, I need a file for sending over Wifi. You can use a file inside your app as assets, from SdCard Or create general FilePicker.
I set an image from /sdcard/Download/ directory. @onCreate(Bundle)
Code:
File [B][COLOR="Red"]fileToSend [/COLOR][/B]= new File(Environment.getExternalStorageDirectory().getPath() + "/Download/shuttle.jpg");
Now, You should initialize instance WifiP2pManager @onCreate(Bundle)
Code:
WifiP2pManager wifiManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
Channel wifichannel = wifiManager.initialize(this, getMainLooper(), null);
Then, You should Register a BroadcastReceiver with proper IntentFilter Actions.
Code:
IntentFilter wifiClientReceiverIntentFilter = new IntentFilter();
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
registerReceiver([B]ClientReceiver[/B]/*I will edit receiver later*/, wifiClientReceiverIntentFilter);
After this, You should invoke Peer Descovery. Also, It makes device discoverable
Code:
wifiManager.discoverPeers(wifichannel, new WifiP2pManager.ActionListener() {
public void onSuccess() {
//done
}
public void onFailure(int i) {
}});
And wait in ClientReceiver to setup peers. But, It is better to create a function in ClientActivity & pass instance of activity to receiver to access the functions. Check Sample Codes
Code:
public void [B][COLOR="red"]listOfPeers[/COLOR][/B](final WifiP2pDeviceList peers) {
ListView peerView = (ListView) findViewById(R.id.peers_listview);
ArrayList<String> peersStringArrayList = new ArrayList<String>();
for(WifiP2pDevice wd : peers.getDeviceList()) {
peersStringArrayList.add(wd.deviceName);
}
peerView.setClickable(true);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, peersStringArrayList.toArray());
peerView.setAdapter(arrayAdapter);
peerView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int arg2,long arg3) {
TextView tv = (TextView) view;
WifiP2pDevice device = null;
for(WifiP2pDevice wd : peers.getDeviceList()) {
if(wd.deviceName.equals(tv.getText()))
device = wd;
}
[B][COLOR="red"]if(device != null) {
/*Connect to first Device*/
targetDevice = device;
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
wifiManager.connect(wifichannel, config, new WifiP2pManager.ActionListener() {
public void onSuccess() {}
public void onFailure(int reason) {}
});
}[/COLOR][/B]
}});}
Open ClientReceiver to request list of peers when proper action occurs Check Sample Codes
Code:
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
manager.requestPeers(channel, new WifiP2pManager.PeerListListener() {
public void onPeersAvailable(WifiP2pDeviceList peers) {
[COLOR="DarkOrchid"]activity[/COLOR].[B][COLOR="red"]listPeers[/COLOR][/B](peers);
}});
}
I set codes for connecting to a peer. But rewrite it here to consider it here in details
Code:
public void connectToPeer(final WifiP2pDevice wifiPeer){
targetDevice = wifiPeer;
/*[COLOR="Red"]Wi-Fi P2p configuration for setting up a connection[/COLOR]*/
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = wifiPeer.deviceAddress;
wifiManager.connect([COLOR="red"]wifichannel[/COLOR], [COLOR="red"]config[/COLOR], new WifiP2pManager.ActionListener() {
public void onSuccess() {}
public void onFailure(int reason) {}
}); }
Now, It is time to perform sending actions in ClientService and for this you should pass required info to service to open socket and write on it...
Port Number
WifiP2pInfo
File
So, After registering a receiver to get information when proper actions occur & getting list of peers, connection stablished & Now you can write data to Socket.OutputStream
Code:
Intent clientServiceIntent = new Intent(this, ClientService.class);
clientServiceIntent.putExtra("fileToSend", [B][COLOR="red"]fileToSend[/COLOR][/B]);
clientServiceIntent.putExtra("port", Integer.valueOf([B][COLOR="red"]port[/COLOR][/B]/*set what you want*/));
clientServiceIntent.putExtra("wifiInfo", [B][COLOR="Red"]wifiInfo[/COLOR][/B]);
startService(clientServiceIntent);
Then Open ClientService & set to get passed data
Code:
port = (Integer) intent.getExtras().get("port");
fileToSend = (File) intent.getExtras().get("fileToSend");
clientResult = (ResultReceiver) intent.getExtras().get("clientResult");
wifiInfo = (WifiP2pInfo) intent.getExtras().get("wifiInfo");
Now you can define socket and try to write data.
Before that you need proper address of target device
Code:
InetAddress [COLOR="RoyalBlue"]targetIP [/COLOR]= [B][COLOR="red"]wifiInfo[/COLOR][/B].groupOwnerAddress;
Now you can open socket and writing data Check Sample Codes
Code:
try {
Socket clientSocket = new Socket([B][COLOR="royalblue"]targetIP[/COLOR][/B], [B][COLOR="Red"]port[/COLOR][/B]);
OutputStream os = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
InputStream is = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
byte[] buffer = new byte[4096];
FileInputStream fis = new FileInputStream(fileToSend);
BufferedInputStream bis = new BufferedInputStream(fis);
[B][COLOR="RoyalBlue"]while(true) {
int bytesRead = bis.read(buffer, 0, buffer.length);
if(bytesRead == -1) {break;}
[SIZE="4"]os.write(buffer,0, bytesRead);[/SIZE]
os.flush();
}[/COLOR][/B]
fis.close();
bis.close();
br.close();
isr.close();
is.close();
pw.close();
os.close();
clientSocket.close();
}
catch(Exception e) {e.printStackTrace();}
. Wifi Direct | Server
First, Register a BroadcastReceiver with Same IntentFilter Actions to get notification of connection information & specify a Path to store receiving data
Code:
/*this should be a directory*/
File downloadTarget = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/");
Then start service and pass required data and prepare it to listen on socket with same port
Path to Store Data
Port Number
Code:
Intent serverServiceIntent = new Intent(this, ServerService.class);
serverServiceIntent.putExtra("saveLocation", downloadTarget);
serverServiceIntent.putExtra("port", Integer.valueOf(port));
startService(serverServiceIntent);
Now you can accept socket from specified port on server side and listen to read data Check Sample Codes
Code:
try {
[B][COLOR="royalblue"]ServerSocket welcomeSocket = new ServerSocket(port);
Socket socket = welcomeSocket.accept();[/COLOR][/B]
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String inputData = "";
String savedAs = "WifiDirectDemo." + System.currentTimeMillis();
File file = new File(saveLocation, savedAs);
byte[] buffer = new byte[4096];
int bytesRead;
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
/*[B][COLOR="Red"]Read data from Socket & Write it to a file[/COLOR][/B]*/
while(true)
{
bytesRead = is.read(buffer, 0, buffer.length);
if(bytesRead == -1){break;}
bos.write(buffer, 0, bytesRead);
bos.flush();
}
bos.close();
socket.close();
}
catch(Exception e) {e.printStackTrace();}
Download Source Code & Enjoy
If you find any mistake Or issue in my codes Please inform me
Click to expand...
Click to collapse
Don't forget to Hit Thanks
NFC [Data Transferring][Send File][Write Data to NFC Tag][Read Data from NFC Tag]
Android allows you to transfer large files between devices using the Android Beam file transfer feature. This feature has a simple API and allows users to start the transfer process by simply touching devices. In response, Android Beam file transfer automatically copies files from one device to the other and notifies the user when it's finished.
Click to expand...
Click to collapse
NFC (Near Field Communication) is the best way to transfer important data.
The data can be simple URI of File (Image & etc) from your SdCard, Info of Music Track Or Bank Account Information for transferring money.
And I think, It will be inside all electronic devices in near future.
Read More
Different Usage of NFC | How Secure is NFC
What is NFC Tag
You will learn How to...
I. Transfer Simple File to another Device by NFC
II. Write Data to NFC Tag
III. Read Data from NFC Tag
Click to expand...
Click to collapse
### Let Start Coding ###
. Send a File
Create a Project on Android Studio. Set minSdk to API 16 & Open AndroidManifest.xml to add required permissions and features
Code:
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.BIND_NFC_SERVICE"/>
<uses-feature android:name="android.hardware.nfc" android:required="true" />
Open layout.xml and add <Button /> & <ImageView/> whereever you like.
Then Open Activity.Java to initialize NfcAdapter & Set URI of Data.
For example, I used a simple ImagePicker to get URI of Image File and set it for NFC transferring.
Code:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 143);
/*then call [COLOR="Red"]onActivityResult[/COLOR] to get URI of file*/
}
});
After clicking on ImagePicker Button, it will redirect you to select an image. Then you will back to the app and get information of the picked image. Also, you can define Uri imageUri; to store the data and use is later.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 143:
if(resultCode == RESULT_OK){
try {
/*this is what app need to set for nfc*/
/*you can also set it to nfcAdapter here*/
[B][COLOR="red"]Uri imageUri[/COLOR];[/B] = imageReturnedIntent.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
}
catch (FileNotFoundException e) {e.printStackTrace();}
}}}
You can also set the URI to nfcAdapter here. I set when image show to user and He/She get what exactly going on and then by clicking on ImageView confirm & set it to NfcAdapter.
Code:
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*NfcAdapter init*/
[B]nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());[/B]
// Check whether NFC is enabled on device
if(!nfcAdapter.[B]isEnabled[/B]()){
// NFC is disabled, show the settings to enable NFC
Toast.makeText(getApplicationContext(), "Turn On NFC", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
// Check whether Android Beam feature is enabled on device
else if(!nfcAdapter.[B]isNdefPushEnabled[/B]()) {
// Android Beam is disabled, show the settings to enable Android Beam
Toast.makeText(getApplicationContext(), "Enable Android Beam", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
}
else {
// NFC and Android Beam both are enabled
if (imageUri != null) {
/*URI if File set to NfcAdapter for transfering*/
nfcAdapter.setBeamPushUris(new Uri[]{[B][COLOR="red"]Uri imageUri[/COLOR];[/B]}, MainActivity.this);
}
else {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 143);
}
}}});
Now, users should touch their devices and wait for files.
Check out this line.
Code:
nfcAdapter.setBeamPushUris(new Uri[]{[B][COLOR="red"]Uri imageUri[/COLOR];[/B]}, MainActivity.this);
You can call it whenever you want & as you can see, there can be several URI of files.
. Write Data to NFC Tag
There is no additional permissions & features for this. Check If your NFC Tags are Writable.
Initialize NfcAdapter @oncreate(Bundle)
Code:
NfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
Then add <Intent-filter/> to detect NFC connections. I set filters as a PendingIntent [COLOR="RoyalBlue" [user=815433]@onres[/user]ume()[/COLOR][/B]
[CODE]IntentFilter ACTION_TAG_DISCOVERED = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ACTION_NDEF_DISCOVERED = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter ACTION_TECH_DISCOVERED = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{ACTION_TAG_DISCOVERED, ACTION_NDEF_DISCOVERED, ACTION_TECH_DISCOVERED};
PendingIntent pendingIntent = PendingIntent.
getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(nfcAdapter != null) {
[B]nfcAdapter[/B].[COLOR="red"]enableForegroundDispatch[/COLOR](this, pendingIntent, nfcIntentFilter, null);
/*enableForegroundDispatch; This will give give priority to the foreground activity when dispatching a discovered Tag to an application.*/
}
[/CODE]
Now, you can detect when NfcTag touch your device. So you need to initialize NFC.Tag instance & store is in Tag tag;
Code:
@Override
protected void onNewIntent(Intent intent) {
[B][COLOR="red"]tag [/COLOR][/B]= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
I use ImagePicker Button to perform writing action on press and hold.
I will write String of Image URI to NFC tag.
Code:
picker.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if([B][COLOR="red"]tag [/COLOR][/B]!= null) {
Ndef ndef = Ndef.get([B][COLOR="red"]tag[/COLOR][/B]);
if (ndef != null) {
try {
ndef.connect();
NdefRecord mimeRecord = NdefRecord.createMime("text/plain", [B][COLOR="red"]imageUriString[/COLOR][/B].getBytes());
ndef.writeNdefMessage(new NdefMessage(mimeRecord));
ndef.close();
Toast.makeText(getApplicationContext(), "WriteDone!", Toast.LENGTH_LONG).show();
}
catch (Exception e) {e.printStackTrace();}
}
}return true;}});
It is mandatory for all Android devices with NFC to correctly enumerate Ndef on NFC Forum Tag Types 1-4, and implement all NDEF operations as defined in this class.
Click to expand...
Click to collapse
. Read Data from NFC Tag
Initialize NfcAdapter, define PendingIntent with specific NfcAdapter.ACTIONS @onresume() & initialize NFC.Tag.
When you have instance of Tag then you can Read/Write.
Now, I get String of imageURI from NFC.Tag and set image to ImageView.
Code:
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if([B][COLOR="red"]tag [/COLOR][/B]!= null) {
Ndef ndef = Ndef.get([B][COLOR="red"]tag[/COLOR][/B]);
try {
ndef.connect();
NdefMessage ndefMessage = ndef.getNdefMessage();
[B]String nfcInfo = new String(ndefMessage.getRecords()[0].getPayload());
[COLOR="red"]imageUri [/COLOR]= Uri.parse(nfcInfo);[/B]
InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
ndef.close();
Toast.makeText(getApplicationContext(), "ReadDone!", Toast.LENGTH_LONG).show();
}
catch (Exception e) {e.printStackTrace();}
} return true; } });
Download Source Code & Enjoy
If you find any mistake Or issue in my codes Please inform me
Click to expand...
Click to collapse
Don't forget to Hit Thanks
Reserved
Reserved
Index of Data Transferring Tutorials
Latest Data Transferring Tutorial
android Auto | Tutorial
android Wear | Watch-To-Phone Tutorial | Phone-To-Watch Tutorial
android TV | Tutorial
Server Download/Upload | Tutorial
Bluetooth | Tutorial
NFC | Tutorial
Wifi Direct| Tutorial
Don't forget to Hit Thanks