Android examples for Network:NFC
NFC call On Resume
//package com.java2s; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Parcelable; import android.util.Log; public class Main { public static final String TAG = "NFC"; private static boolean mResumed = false; private static NfcAdapter mNfcAdapter; private static PendingIntent mNfcPendingIntent; private static IntentFilter[] mNdefExchangeFilters; public static void callOnResume(Activity activity) { mResumed = true;/*from w w w . j a v a 2 s . c om*/ // Sticky notes received from Android if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(activity.getIntent() .getAction())) { NdefMessage[] messages = getNdefMessages(activity.getIntent()); byte[] payload = messages[0].getRecords()[0].getPayload(); activity.setIntent(new Intent()); // Consume this intent. } enableNdefExchangeMode(activity); } public static NdefMessage[] getNdefMessages(Intent intent) { // Parse the intent NdefMessage[] msgs = null; String action = intent.getAction(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Parcelable[] rawMsgs = intent .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; } } else { // Unknown tag type byte[] empty = new byte[] {}; NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty); NdefMessage msg = new NdefMessage( new NdefRecord[] { record }); msgs = new NdefMessage[] { msg }; } } else { Log.d(TAG, "Unknown intent."); } return msgs; } private static void enableNdefExchangeMode(Activity activity) { mNfcAdapter .enableForegroundNdefPush(activity, getMessageAsNdef("")); mNfcAdapter.enableForegroundDispatch(activity, mNfcPendingIntent, mNdefExchangeFilters, null); } public static NdefMessage getMessageAsNdef(String message) { byte[] textBytes = message.getBytes(); NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(), new byte[] {}, textBytes); return new NdefMessage(new NdefRecord[] { textRecord }); } }