Aymen
Aymen

Reputation: 422

How to avoid launching an NFC-enabled app?

Assuming that I have 2 activities:

  1. MainActivity and
  2. SecondActivity.

What i want to achieve is to pass from MainActivity to SecondActivity by discovering an NFC tag. I made it work by adding the intent-filter to the manifest under the SecondActivity tag.

But my problem is that the app will launch and land to the second activity even if the app is killed. Basically, I want the tag discovery to happen only when I'm in the main activity (after clicking a button to start reading).

I tried adding the intent-filter programatically in the onCreate() method of MainActivity and overriding the onNewIntent() method but with no luck.

I also tried to set the launchMode to "singleTop" without success.

The following is what I added to the onCreate() method of the MainActivity:

adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] { tagDetected };

Upvotes: 0

Views: 1064

Answers (2)

Carlo
Carlo

Reputation: 1579

If I correctly understood your question, the problem is that your activity triggers also when the app is not running.

If this is the point, the problem is that you've declared your activity to be triggered on NFC event in the AndroidManifest.xml file and the solution is to remove the NFC block from the activity declaration in the manifest.

Upvotes: 1

Michael Roland
Michael Roland

Reputation: 40831

You could register for the foreground dispatch in your MainActivity. Then, upon receiving the NFC intent, you can start the SecondActivity and pass the intent to it:

@Override
public void onResume() {
    super.onResume();
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
    PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    adapter.enableForegroundDispatch(this, pendingIntent, null, null);
}

@Override
public void onPause() {
    super.onPause();
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
    adapter.disableForegroundDispatch(this);
}

@Override
public void onNewIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) ||
        NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) ||
        NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Intent newIntent = new Intent(this, SecondActivity.class);
        newIntent.putExtra("NFC_INTENT", intent);
        startActivity(newIntent);
    }
}

Upvotes: 2

Related Questions