Search code examples
javaandroidandroid-launcher

App restarts main activity from background instead of resuming previous state


If I launch the app from the home screen (by taping the app icon), then I navigate through the app and then I leave the app, when I reopen the app the same way (by taping the app icon from the home screen) it will resume the previous state and show the last activity I was on before leaving the app. That part works as expected.

Here is the issue:

If I first launch the app from the play store or manually from the apk installer, and then reopen the app another way (by taping the app icon from the home screen for instance), the app will start a new instance of the main activity and will add it the previous navigation stack (If I press the back button it will go back to the last activity I was on before leaving the app).

I always want the app to open the last activity from background, no matter how the app was first launched (via the home screen or the play store or manually). I already tried stuff like that in the main activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!isTaskRoot()
        && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
        && getIntent().getAction() != null
        && getIntent().getAction().equals(Intent.ACTION_MAIN)) {

        finish();
        return;
    }
    [...]
}

but the finish() call crashes the app.


Solution

  • I actually found why finish() crashed the app: onDestroy() was called and it tried to unregister a receiver that was not registered yet, so the app crashed: Unable to destroy activity [...] Receiver not registered.

    So that code actually works fine for my issue:

    if (!isTaskRoot()
            && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
            && getIntent().getAction() != null
            && getIntent().getAction().equals(Intent.ACTION_MAIN)) {
    
        finish();
        return;
    }
    

    I just didn't pay attention to onDestroy()