Dim
Dim

Reputation: 4807

Prevent reopen activity on NFC read

I have an activity that opens on NFC read. I added timer when the activity should close. My main goal that the user will get the info and the app will close. What I am trying to is prevent the activity open when the current activity is running (when timer runs, prevent second NFC read). I have added Boolean in shared preference for this, but with no luck. The activity is opens. Can you suggest me solutions for this problem?

public class NFCTagger extends AppCompatActivity {

    private static final String TAG = "DTAG";
    NfcAdapter nfcAdapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    Tag myTag;
    Context context;
    TextView tvNFCContent;
    Preference prefs;

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

        context = this;
        prefs = new Preference(context);

        Log.d(TAG,"NFCTagger: OnCreate");

        setContentView(R.layout.activity_nfctagger);
        tvNFCContent = findViewById(R.id.textViewNFC);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        if (nfcAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        }

        if (!prefs.getBool(Preference.IN_NFC_SCREEN))
        {
            prefs.setBool(Preference.IN_NFC_SCREEN,true);
            readFromIntent(getIntent());

        }

        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};
    }

    //Read NFC Tag

    private void readFromIntent(Intent intent) {

        Log.d(TAG,"Read from intent");
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            try {
                buildTagViews(msgs);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private void buildTagViews(NdefMessage[] msgs) throws ParseException {


        if (msgs == null || msgs.length == 0)
            return;

        byte[] payload = msgs[0].getRecords()[0].getPayload();

        String text = "";
        try {
            text = new String(payload, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String currentTime = timeFormat.format(new Date());
        tvNFCContent.setText(currentTime);


        final Toast mToast = Toast.makeText(context, "", Toast.LENGTH_LONG);
        mToast.show();

        new CountDownTimer(6000, 1000) {

            public void onTick(long millisUntilFinished) {
                mToast.setText("Closing in: " + millisUntilFinished / 1000);
            }

            public void onFinish() {
                prefs.setBool(Preference.IN_NFC_SCREEN,false);
                finish();
            }
        }.start();

    }

    private void clearNFCPrefs()
    {
       prefs.setString(Preference.NFC_ARRIVAL,null);
        prefs.setString(Preference.NFC_EXIT,null);
        prefs.setString(Preference.NFC_ARRIVAL_DATE,null);
    }


    @Override
    public void onPause() {
        super.onPause();
        Log.d("DTAG","NFCTagger onPause");
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("DTAG","NFCTagger onResume");
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        Log.d("DTAG","NFCTagger onNewIntent");
        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

}

Manifest:

 <activity android:name=".activities.NFCTagger">
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="application/vnd"/>
            </intent-filter>

            <meta-data
                android:name="android.nfc.action.TECH_DISCOVERED"
                android:resource="@xml/nfc_tech_filter" />

        </activity>

Upvotes: 1

Views: 752

Answers (2)

Constantin
Constantin

Reputation: 218

In your statement you're saying you're using SharedPreferences, but in your code you're using Preference. These are two different things.

Try SharedPreferences instead and:

  • to save use prefs.edit().putBoolean("your-key", yourValue).commit()
  • to read prefs.getBoolean("your-key", defaultValue)

Upvotes: 0

Mohamed Hamdaoui
Mohamed Hamdaoui

Reputation: 359

I think what you are looking for is making the activity a Single Task, by adding this to you Activity declaration in the manifest: android:launchMode="singleTask"

Upvotes: 2

Related Questions