I got an application that reads and writes nfc tags with ndef data format. This all seems to be ok. But whenever i try to get closer a tag to my phone, it produces a new act
Instead of setting the launch-mode of the activity that receives the NFC intents to "singleTask" (see CommonsWare's answer), the preferred way for NFC applications to receive NFC-related intents while the app is in foreground is the foreground dispatch system (or alternatively the reader mode API when using only Android 4.4).
In order to use the foreground dispatch, you would create a pending intent like this:
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
0);
Then, in your activity's onResume()
method, you would enable the foreground dispatch like this:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
You will then receive intents notifying you about discovered tags through the activity's onNewIntent()
method:
public void onNewIntent(Intent intent) {
...
}
Moreover, you have to disable the foreground dispatch in your activity's onPause()
method:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.disableForegroundDispatch(this);
Add android:launchMode="singleTask"
to the <activity>
element for MainActivity
. Note that if the activity is already running, onNewIntent()
will be called, instead of onCreate()
, to deliver the NDEF Intent
to you. Hence, you will need to handle the NDEF Intent
in both onCreate()
(if the activity was not already running) and onNewIntent()
(if the activity was already running).
This sample project illustrates the technique.