簡體   English   中英

Android:啟動同一個實例

[英]Android: launch same instance

我正在使用以下代碼創建Home快捷方式:我想啟動應用程序的相同打開實例(如果存在),而不是新實例。

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

}

Android框架會按照預定義的Activity生命周期銷毀並重新創建活動。 當用戶看不到某項活動時,該活動很可能已被破壞,並且肯定已被“暫停”。 但是,如果您希望在某個實例之間維護某個活動的實例,則可以將這些工件放置在通過onSaveInstanceState方法重寫傳遞給該活動的onCreate的Bundle中。 這允許在與活動狀態相同的狀態下重新創建活動,例如恢復部分填寫的表單,而不是在重新創建過程中忘記用戶輸入。 “后棧”可能會采用一種不同的機制,而我並非100%參與其中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM