NFC P2P tag intercept

本小妞迷上赌 提交于 2019-12-12 05:41:08

问题


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:

  1. 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);
    
  2. Do something upon receiving the intent:

    public void onNewIntent(Intent intent) {
        ...
    }
    


来源:https://stackoverflow.com/questions/30186739/nfc-p2p-tag-intercept

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!