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

China☆狼群 提交于 2019-12-12 13:36:37

问题


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!


回答1:


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."




回答2:


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



来源:https://stackoverflow.com/questions/31813322/android-launchmode-singletop-not-working-if-app-opened-from-another-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!