Disable beam touch mode

2019-04-16 12:04发布

问题:

I have an app where a special Activity A is able to transfer data:

When Device1 is in Activity A and you pair it with Device2 (no matter where Device2 is, even if the app is not started) the data is successfully transfferred after the beam touch. Activity A has the intent filter:

       <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="application/de.my.app" />
        </intent-filter>

on does the necessary push.

But when I am in another activity B, this also makes

  1. The other device start the app
  2. Make the touch mode appear on both devices if the app is started. I dont want any device have the change to do the beam now. If you are on the android desktop and you pair the devices, you do not get the beam dialog too. You just get a small vibration. Thats what I want here. Is it possible?

Thanks in advance!

回答1:

In Activity B, you can turn on foreground-dispatching, ignore any NFC intents and disable sending Android Beam messages:

private NfcAdapter nfcAdapter;

protected void onCreate(Bundle savedInstanceState) {
  ...
  nfcAdapter = NfcAdapter.getDefaultAdapter(this);
  // turn off sending Android Beam
  nfcAdapter.setNdefPushMessage(null, this);
}

protected void onResume() {
  // catch all NFC intents
  Intent intent = new Intent(getApplicationContext(), getClass());
  intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
  nfcAdapter.enableForegroundDispatch(this, pintent, null, null);
}

protected void onPause() {
  nfcAdapter.disableForegroundDispatch(this);
}

protected void onNewIntent(Intent intent) {
  if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) {
    return; // ignore NFC intents
  }
}

You could make this a little more specific by filtering only for the Ndef technology in the PendingIntent and/or checking in the onNewIntent() what other technologies the Tag object supports. Android Beam intents always have the Ndef technology and no other ones.