In my app I am using NFC to read tags. I click on the button to enable NFC. A progress dialog is opened to read the NFC tag, and when done, NFC is disabled. That's all working fine. But when NFC is not enabled in the app and I put a NFC tag to the phone, the default Android app reads the NFC tag and puts my app to the background.
How can I disable the Android app?
My code for enabling / disabling NFC:
/**
* @param activity The corresponding {@link Activity} requesting the foreground dispatch.
* @param adapter The {@link NfcAdapter} used for the foreground dispatch.
*/
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{};
// Notice that this is the same filter as in our manifest.
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
filters[0].addDataType(MIME_TEXT_PLAIN);
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException(activity.getString(R.string.exception_wrong_mime_type));
}
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
/**
* @param activity The corresponding {@link MainActivity} requesting to stop the foreground dispatch.
* @param adapter The {@link NfcAdapter} used for the foreground dispatch.
*/
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
You can't disable this behavior. Another app is launched because your app doesn't catch the tag. When you delete the app this will stop, but ofcourse that's not the solution.
If you want to prevent this you should catch the scanned tag in your app, which is on the foreground.
You already know how to do this with enableForegroundDispatch
. Don't disable the foreground dispatch when a tag is scanned, but create a flag or something which determines if you want to do something with the tag or not.
For example:
doSomethingWithTheTag
doSomethingWithTheTag
should be true
. If it's false
don't do something with the tag. In most cases, this will be your onNewIntent
override, just make sure every activity overrides that function.doSomethingWithTheTag
to true
doSomethingWithTheTag
to false
Hope i'm clear. Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With