简体   繁体   中英

Android: launch same instance

I am creating a Home shortcut with the following code: I would like to get the same opened instance (if exist) of the app launched and not a new instance.

    public void createShortcut() {

    if (app.prefs.getBoolean("prefs_ShortcutCreated", false) == false) {
        Intent shortcutIntent = new Intent();
        shortcutIntent.setClassName(this, this.getClass().getName());

        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        Intent addIntent = new Intent();
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "test");
        addIntent.putExtra("duplicate", false);
        File image = new File(app.DEFAULT_APP_FOLDER_MAIN, "icon.png");
        AssetManager assets = app.getApplicationContext().getResources().getAssets();
        try {
            copy(assets.open("icon.png"), image);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Bitmap theBitmap = BitmapFactory.decodeFile(app.DEFAULT_APP_FOLDER_MAIN + "icon.png");
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(theBitmap, 128, 128, true);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, scaledBitmap);

        addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        sendBroadcast(addIntent);

        theBitmap.recycle();
        scaledBitmap.recycle();

        Editor editor = app.prefs.edit();
        editor.putBoolean("prefs_ShortcutCreated", true);
        editor.commit();
    }

}

The Android Framework destroys and re-creates activities following the pre-defined Activity lifecycle. When an activity is not visible to the user it has more than likely been destroyed, and has definitely been 'paused'. However, should there be something about an instance of an activity you wish to maintain across instances you can place those artefacts in the Bundle delivered to the Activity's onCreate via the onSaveInstanceState method override. This allows the activity to be re-created in the same state as it was left eg to restore a partially filled in form instead of forgetting the user inputs during the re-create. The 'back stack' may employ a different mechanism that I'm not 100% on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM