问题
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"
inmanifest.xml
- I tried the same with
launchMode=singleTask
, but it has the same behaviour - used additional
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
on everyIntent
which starts a newActivity
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 MainActivity
if 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