[Android Software Development] Geeks Empire:
NFC [Data Transferring][Send File][Write Data to NFC Tag][Read Data from NFC Tag]

[IMG="nfc"]https://xdaforums.com/attachment.php?attachmentid=4283694&d=15064090609125[/IMG]​

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​

### 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

<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.

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.

@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.

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.

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 [MENTION=530167]onc[/MENTION]reate(Bundle)

NfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());

Then add <Intent-filter/> to detect NFC connections. I set filters as a PendingIntent [COLOR="RoyalBlue" [MENTION=815433]onres[/MENTION]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;

@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.

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;}});

. Read Data from NFC Tag

Initialize NfcAdapter, define PendingIntent with specific NfcAdapter.ACTIONS [MENTION=815433]onres[/MENTION]ume() & 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.

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

Don't forget to Hit Thanks​