Search code examples
javaandroidnfcalarmmanageralarm

How to close my App when an NFC tag is detected


I am developing an alarm clock app that will allow you to turn off the alarm only if the app has detected an NFC tag. The tags I am using have nothing written to them I believe (when the phone detects the NFC tag it says "Empty tag"). Here is my code and was wondering if you could help! Android Manifest:

    <intent-filter>
    <action android:name="android.nfc.action.TAG_DISCOVERED" />
</intent-filter>

Code:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Wake Log");
        mWakeLock.acquire();
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_FULLSCREEN |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        setContentView(R.layout.normal_alarm);

        if (NfcAdapter.ACTION_TAG_DISCOVERED.isEmpty() == false){
            NewAlarm.time = "";
            NewAlarm.date = "";
            mMediaPlayer.stop();
            finish();
        }
        playSound(this, getAlarmUri());

Solution

  • The TAG_DISCOVERED intent when used in the app's manifest is meant as a fall-back mechanism that is triggered only if no other app registered for more suitable NFC intents. So unless you develop for Android 2.3 (where TAG_DISCOVERED was the main NFC intent to use) you should avoid using this as the only NFC-related intent filter.

    However, in your case (the app is already open as I understand it) you can skip intent filtering in the manifest completely. While your app is in the foreground, you should register for the foreground tag dispatch system.

    Also note that

    if (NfcAdapter.ACTION_TAG_DISCOVERED.isEmpty() == false){
    

    does not really make sense as NfcAdapter.ACTION_TAG_DISCOVERED is a string constant that always contains the value android.nfc.action.TAG_DISCOVERED. So it will never be empty.