Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: launchMode singleTop not working if app opened from another app

I have an application, which misbehaves if started from another app (e.g. over the playstore). Instead of resuming to the already existing Activity, it restarts as a new instance.

What I have:

  • declared every activity with launchMode="singleTop"in manifest.xml
  • I tried the same with launchMode=singleTask, but it has the same behaviour
  • used additional intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) on every Intent which starts a new Activity
  • onNewIntent() is not called in already running instance

I used following code, to start my app from another app (with, and without additional addFlag())

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("my.package.name");
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(launchIntent);

My Launcher-Activity is a SplashScreenActivity, which starts the MainActivityif user is logged in with the following code and gets finished()

 Intent intent = null;
 intent = new Intent(SplashScreenActivity.this, HomeActivity.class);
 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
 startActivity(intent);
 finish();

What am I missing? Any recommendations are welcome!

like image 749
longi Avatar asked Mar 15 '23 04:03

longi


2 Answers

After some more researches, I added following code in the SplashScreenAvtivity:onCreate()

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

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

}

This dismisses SplashScreenActivity, if App is already running. This works with all launch-modes

like image 68
longi Avatar answered May 08 '23 20:05

longi


Please try using singleTask instead of singleTop for SplashScreenActivity. As per http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

"The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one."

like image 20
shivam gupta Avatar answered May 08 '23 20:05

shivam gupta