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