2

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.

TtT23
  • 6,876
  • 34
  • 103
  • 174

2 Answers2

2

I think you can try to do something with ACTION_SCREEN_ON :

  • register a receiver for it (you need to it in code, it won't work in manifest).
  • in the onReceive do something like:

MY_FLAG_JUST_WAKE_UP = true;

and in the onResume() :

if(!MY_FLAG_JUST_WAKE_UP){
  doStuff();
}
MY_FLAG_JUST_WAKE_UP = false;

But, it need to be tested, I don't know if you will always receive the intent before the onResume() get called.

ben75
  • 29,217
  • 10
  • 88
  • 134
2

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.

NFC guy
  • 10,151
  • 3
  • 27
  • 58