Method onNewIntent(intent) not executing in NFC

Your code works fine when your activity is on foreground, but it won't work when the Activity is started by an Intent with android.nfc.action.XXX_DISCOVERED action. As it is the first intent, onNewIntent() won't be called, but you can use the intent in your onCreate() method. You should call your NFC logic from onCreate() and from onNewIntent(), validating the action before accessing the tag.

public class NFCActivity extends Activity {

    private NfcAdapter mNFCAdapter;
    private PendingIntent mNfcPendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        performTagOperations(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        performTagOperations(intent);
    }

    private void performTagOperations(Intent intent){
        String action = intent.getAction();
        if(action.equals(NfcAdapter.ACTION_TAG_DISCOVERED) ||
        action.equals(NfcAdapter.ACTION_TECH_DISCOVERED) ){
            //PERFORM TAG OPERATIONS
        }
    }
    ...
}

In my case the problem was, that I followed the documentation for nfcAdapter.enableForegroundDispatch(...) blindly and I pasted this code into fragment:

pendingIntent = PendingIntent.getActivity(
            this,
            0,
            new Intent(this, getClass())
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

Since it actually expects activity, just change all to this to getContext() and especially getClass().

pendingIntent = PendingIntent.getActivity(
            getContext(),
            0,
            new Intent(getContext(), getContext().getClass())
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

Tags:

Android

Nfc