Search code examples
javaandroidnfcnfc-p2p

How to determine if the device has been waked up from sleep mode inside onResume


Is there anyway to check if onResume was called from the device waking up from sleep state in Android?

The reason why I need to check that is I don't want it to call a particular method if resumed from sleep state:

@Override
public void onResume() {
    super.onResume();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())
        && !SomeCrazyMethodOrPropertyCheckingIfDeviceWakedUpFromSleep) {
        processIntent(getIntent());
    }
}

You might say "Take that processintent method out of onResume"... It's not an option, NFC P2P mode requires you to process the received NDEF message inside onResume.


Solution

  • I would recommend overriding onNewIntent() to handle the NFC intents:

    @Override
    public void onNewIntent(final Intent intent) {
      setIntent(intent);
      if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        processIntent(intent);
      }
    }
    

    In processIntent() you can check whether the intent was handled already:

    private void processIntent(final Intent intent) {
      if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
    //  Log.v(TAG, "Ignoring intent; already treated this intent.");
        return;
      }
      intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
      // new intent; process it
      ...
    }
    

    Likely this will solve your problem.