1

If you press the home button on an Android device and then you call startActivity() it will silently fail and there doesn't seem to be a way to check when it fails. For example:

@Override
protected void onStop() {
    super.onStop();
    
    Handler hndlr = new Handler();
    Runnable t = new Runnable() {
        public void run() {
            startActivity(new Intent(getApplicationContext(), SomeOtherActivity.class)); //this silently fails, no error, nothing
        }
    };
    hndlr.postDelayed(t, 1000);
}

Is there a way to check if it fails to start the activity? I don't intend to start any activity in the background, I just need to know when it fails. Please note that this only happens when you press the home button, I'm actually not sure if this is just an Android bug (I'm testing on Android 11). Thanks!

eXistenZ
  • 326
  • 4
  • 14
  • 1
    Actually it fails within around 5 seconds after user leaves your apps. It's intended to prevent malicious apps from blocking user from leaving them (in order to blackmail them or whatever) I'm not sure if this limitations added since Android 9 or 10 but check this out https://stackoverflow.com/questions/5600084/starting-an-activity-from-a-service-after-home-button-pressed-without-the-5-seco – Amin Oct 08 '21 at 01:25
  • Ahh, it makes sense now, thanks for clearing this up! Still would be nice to be able to check when it fails. – eXistenZ Oct 08 '21 at 01:40
  • You probably can use a watchdog timer for that – Amin Oct 08 '21 at 01:47

1 Answers1

1

You could just check that your app is in the foreground like this:

if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)){
       startActivity(new Intent(getApplicationContext(), SomeOtherActivity.class));
}
Gavin Wright
  • 3,124
  • 3
  • 14
  • 35
  • I am actually using a boolean and set it to true in onResume() and check it like that, but it still somehow gets called and fails. I believe it takes some time after startActivity is called to create the activity so there's time for it to fail. See Amin's comment above, seems to be a security thing, thanks! – eXistenZ Oct 08 '21 at 01:45