Android:启动相同的实例

标签 android

我正在使用以下代码创建主页快捷方式: 我想要启动应用程序的相同打开实例(如果存在),而不是新实例。

    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 生命周期销毁和重新创建 Activity。当一个 Activity 对用户不可见时,它很可能已被销毁,并且肯定已被“暂停”。但是,如果您希望跨实例维护某个 Activity 的实例,您可以将这些 Artifact 放在 Bundle 中,通过 onSaveInstanceState 方法覆盖传递给 Activity 的 onCreate .这允许以与离开时相同的状态重新创建 Activity ,例如恢复部分填写的表单,而不是在重新创建期间忘记用户输入。 “后退堆栈”可能采用了一种我不是 100% 支持的不同机制。

关于Android:启动相同的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10701462/

相关文章:

android - gradle 文件和我的项目中的导入错误

javascript - OnClick 的蓝色覆盖

android - 向现有用户提供免费的应用内购买

android - 如何限制钛中捕获的视频大小(20MB 到 30MB)?

android - 如何在不创建新应用程序的情况下从生产中取消发布应用程序并在 Google Play 中重新发布测试版?

java - 从 JSONArray 转换为 String 然后再转换回来

android - 如果在应用程序安装后选择“打开”或“完成”,Android 的调用有何不同?

Android onLocationChanged 最快每秒只调用一次

java - 使用 urlConnection.getOutputStream() 获取主机时出现问题;在我的真实设备上

android - 如何在底部对话框 fragment 中将稀松布更改为不可见?