From what you describe, I would assume that your affected users "close" (actually hide) the app by pressing the home key. Later they are opening the app (or rather that activity) from the history (long-press home key).
Assuming that you process the NFC-related intents only in onCreate()
, you would normally not run into the issue you described when starting your activity from the history as the onCreate()
method would not be called if your activity still existed in the background. But if your activity has been destroyed meanwhile (e.g. app has been manually killed, app has been killed by the system to free resources, etc), re-launching the app from the history will cause your onCreate()
method to be run again. As Android rebuilds the activity stack and re-sends the original intents (i.e. the intent that initially launched your activity) again when opening apps from the history, you activity will receive the NFC intent that it had received when it was initially started.
You can overcome this problem by checking if the intent you receive has the FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
set. This would be the case only if your activity was started from the history.
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
...
}
}
Not solving your initial problem but as a last resort, remember that NFC tags can be accessed by IO operations after receiving an intent. So in order to check if the tag you receive in the intent actually exists, you could perform such an IO operation.
If, for instance, your tag is an NDEF tag:
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndefTag = Ndef.get(tag);
try {
ndefTag.connect(); // this should already perform an IO operation and should therefore fail if there is no tag
NdefMessage ndefMsg = ndefTag.getNdefMessage(); // this reads the current NDEF message from the tag and consequently causes an IO operation
} catch (Exception e) {
// there is no tag or communication with tag dropped
} finally {
try {
ndefTag.close();
} catch (Exception e) {
}
}
For non-NDEF tags, you would need to know how to access the tag using low-level commands though. But at least the connect test would work for any tag.