Finally I find the correct way to do this, in one word this is a bug in android and a workaround may be following
if(!isTaskRoot()){
finish();
return;
}
add the code above in your LaucherClass's onCreate
题
I have create a android shortcut via the following code
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,getString(R.string.app_name)); Intent shortcutIntent = new Intent(); shortcutIntent.setClassName(this,MainActivity.class.getName()); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); shortcut.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); shortcut.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); sendBroadcast(shortcut);
when i open my app and finally in some Activity like BActivity,then i switch to home screen and click the shortcut , the app come to MainActivity as the code above , can i have a chance to avoid this and just let the app come in foreground if it's already created ?
解决方案
Finally I find the correct way to do this, in one word this is a bug in android and a workaround may be following
if(!isTaskRoot()){
finish();
return;
}
add the code above in your LaucherClass's onCreate
其他提示
You can do this using Shared Preferences.
So in every activity you want to re-start automatically:
@Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.commit();
}
And a Dispatcher activity similar to the following:
public class Dispatcher extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Class<?> activityClass;
try {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
activityClass = Class.forName(
prefs.getString("lastActivity", Activity1.class.getName()));
} catch(ClassNotFoundException ex) {
activityClass = Activity1.class;
}
startActivity(new Intent(this, activityClass));
}
}