Search code examples
androidnfc

How to use NFC to transfer image


I have created a simple app where I have an image. Now what I want to do is.

  1. At first, I want to add NFC support to my app.

  2. Once I add NFC support in my app, the next thing I want is how can I transfer my image that is present in my app to another device having NFC support.

If anyone knows please help me to solve this out, if possible with an example. I have gone through the documentation as provided in developer.android.com for NFC, but in that case, it only gives transfer of text from one device to another using NFC, but in my case I want to transfer image instead of text.

Code for text transfer

public class NFCTestApp extends Activity 
{   
                                
   private NfcAdapter mAdapter;
   private TextView mText;
   private NdefMessage mMessage;

    public static NdefRecord newTextRecord(byte[] text, Locale locale, boolean enco   deInUtf8) 
    {
       byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));

       Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
       byte[] textBytes = text;

       int utfBit = encodeInUtf8 ? 0 : (1 << 7);
       char status = (char) (utfBit + langBytes.length);

       byte[] data = new byte[1 + langBytes.length + textBytes.length]; 
       data[0] = (byte) status;
       System.arraycopy(langBytes, 0, data, 1, langBytes.length);
       System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);

       return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
    }

    public void onCreate(Bundle savedInstanceState) 
    {
       super.onCreate(savedInstanceState);
       mAdapter = NfcAdapter.getDefaultAdapter(this);

       setContentView(R.layout.main);

       
       Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       bm.compress(Bitmap.Compress.JPEG, 100, baos);
       byte[] b = baos.toByteArray();

      // Create an NDEF message 
       mMessage = new NdefMessage(
            new NdefRecord[] { newTextRecord(b, Locale.ENGLISH, true)});  
    }

    @Override
    public void onResume() 
    {
       super.onResume();
       if (mAdapter != null) mAdapter.enableForegroundNdefPush(this, mMessage);
    }

    @Override
    public void onPause() 
    {
       super.onPause();
       if (mAdapter != null) mAdapter.disableForegroundNdefPush(this);
    }
}

Solution

  • First, you need to include this in your manifest file to enable NFC support:

    <uses-permission android:name="android.permission.NFC" />
    <uses-sdk android:minSdkVersion="9" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />
    

    Then you might have a look at NFCDemo, official NFC demo app from Google, for a reference.