防止在NFC读取时重新开启活动

时间:2018-02-02 18:28:01

标签: android android-manifest nfc

我有一项在NFC阅读时打开的活动。当活动应该关闭时,我添加了计时器。我的主要目标是用户将获得信息和应用程序将关闭。我正在尝试阻止活动在当前活动运行时打开(当计时器运行时,阻止第二次NFC读取)。我已经在共享偏好中添加了布尔值,但没有运气。该活动已打开。你能建议我解决这个问题吗?

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

}

清单:

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

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是通过将此活动添加到清单中的活动声明来使活动成为单一任务: android:launchMode="singleTask"

答案 1 :(得分:1)

在您的陈述中,您说您正在使用SharedPreferences,但在您的代码中,您使用的是Preference。这是两件不同的事情。

尝试使用SharedPreferences并:

  • 保存使用prefs.edit().putBoolean("your-key", yourValue).commit()
  • 阅读prefs.getBoolean("your-key", defaultValue)