问题
I am building an Android app using Eclipse and Android SDK. I would like to implement an NFC P2P function in my app in the sense that when you place the 2 phones back to back, both send a string and receive a string automatically. This would of course happen in a separate activity. I have managed to send a custom tag (String) but have been unable to intercept it and use it afterwards in the app code. How can I do this?
This is what I have so far:
public class MainActivity extends Activity {
public NfcAdapter mAdapter;
PendingIntent mPendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = NfcAdapter.getDefaultAdapter(this);
NdefRecord rec = NdefRecord.createUri("www.stackoverflow.com");
NdefMessage ndef = new NdefMessage(rec);
mAdapter.setNdefPushMessage(ndef, this);
}
I have spent a lot of time trying to find and understand solutions to intercept the tag. Unsuccessfully.
Thank you for your help.
回答1:
You can use the foreground dispatch system to receive the NDEF message within your activity:
In
onResume()
:PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
Do something upon receiving the intent:
public void onNewIntent(Intent intent) { ... }
来源:https://stackoverflow.com/questions/30186739/nfc-p2p-tag-intercept