1

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 ?

Minami
  • 893
  • 5
  • 20

2 Answers2

3

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

Minami
  • 893
  • 5
  • 20
0

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));
}

}

Arun Kumar K S
  • 199
  • 1
  • 3
  • 13
  • thank u Arun,but i still wonder if there is a more convenient way to do this,because when you click the icon in the app drawer,the app come to foreground with the exists activity stack,what i want to do is the same,the solution you supplied will destroy the existing activity stack that what i'm avoiding to do ,i think some activity_flag may do this but i read throught the documentation and find few – Minami Aug 29 '13 at 15:06