Search code examples
androidnfc

Stop NFC tag reading after the first time


I'm using NFC to read RFID from passports using jmrtd library. The problem is that I want to stop receiving nfc-related intents after the data is successfully read, but currently even if some other activity is in foreground the app relaunches nfc reading activity again upon tag discovery.

My code:

    protected void onResume() {
        super.onResume();
        this.mAdapter.enableForegroundDispatch(this, this.mNfcListener, mIntentFilters, null);
    }

    //<editor-fold desc="NFC">
    public boolean initNFC() {
        this.mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (this.mAdapter == null) {
            return false;
        }
        Intent i = new Intent(this, getClass());
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        this.mNfcListener = PendingIntent.getActivity(this, 0, i, 0);
        IntentFilter tagFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        this.mIntentFilters = new IntentFilter[]{tagFilter, ndefFilter};
        return true;
    }

    protected void onPause() {
        mAdapter.disableForegroundDispatch(this);
        super.onPause();
    }

Solution

  • that is impossible... because your activity has intent filter action NDEF_DISCOVERED.

    read this... How to detect NFC tag was removed