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 activity. I only want to obtain data on the tag without opening new intent. So i can make my app decide whether the tag has been tapped two times in a row.
The code that i handle coming tags:
public class MainActivity extends Activity {
public static Context myContext;
private Button myButton;
private int currentID, currentBalance;
protected void onCreate(Bundle savedInstanceState) { // Firstly Created when
// a tag tapped to
// the phone
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button1);
currentID = 0;
currentBalance = 0;
myButton.setOnClickListener(new View.OnClickListener() { // Tag write
// function
// places
// here
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), nfcWrite.class);
i.putExtra("id",currentID);
i.putExtra("balance",currentBalance);
startActivity(i);
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Intent intent = getIntent();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefRecord myRecord = ((NdefMessage) rawMsgs[0]).getRecords()[0];
String nfcData = new String(myRecord.getPayload());
String[] splitData = nfcData.split("-");
currentID = Integer.parseInt(splitData[0]);
currentBalance = Integer.parseInt(splitData[1]);
Toast.makeText(getApplicationContext(), nfcData, Toast.LENGTH_LONG).show();
}
}
}
Add
android:launchMode="singleTask"
to the<activity>
element forMainActivity
. Note that if the activity is already running,onNewIntent()
will be called, instead ofonCreate()
, to deliver the NDEFIntent
to you. Hence, you will need to handle the NDEFIntent
in bothonCreate()
(if the activity was not already running) andonNewIntent()
(if the activity was already running).This sample project illustrates the technique.
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:
Then, in your activity's
onResume()
method, you would enable the foreground dispatch like this:You will then receive intents notifying you about discovered tags through the activity's
onNewIntent()
method:Moreover, you have to disable the foreground dispatch in your activity's
onPause()
method: