how to avoid click on android shortcut create new app instance and kill the old one

1.1k views Asked by At

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 ?

1

There are 1 answers

0
钵钵鸡实力代购 On BEST ANSWER

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