我构建了一个可以更改用户壁纸的应用程序。我希望添加一个 Android 快捷方式,这样用户就可以更改他们的墙纸而无需完全打开应用程序(主要用例是将它与 Nova Launcher 之类的手势相关联,它允许您为每个手势选择一个快捷方式) .
我的一切正常,但有一个大问题。每次快捷方式被触发时,我的自定义操作都会发生,但随后主启动 Activity 也会启动!这显然不是我们想要的,我无法弄清楚发生了什么。
这是 ShortcutActivity 代码:
public class ShortcutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
setupShortcut();
finish();
return;
} else {
Toast.makeText(this, "Do something interesting.", Toast.LENGTH_SHORT).show();
finish();
}
}
void setupShortcut() {
Intent shortcutIntent = new Intent("CHANGE");
shortcutIntent.setClass(this, getClass());
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcut_title));
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
setResult(RESULT_OK, intent);
}
}
这是我的(简化的) list :
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/title_activity"
android:theme="@style/AppTheme">
<activity
android:name=".WallpaperSettings"
android:label="@string/title_activity_wallpaper_settings">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ShortcutActivity"
android:theme="@android:style/Theme.NoDisplay"
android:label="@string/shortcut_title">
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
这甚至可以在不触发主启动器 Activity 的情况下完成吗?
最佳答案
我也遇到过。但是我找到了一个可行的解决方案。只需将 android:launchMode="singleInstance"
添加到从您的快捷方式打开的 Activity 中。
在这种情况下:
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main_activity2" >
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT"/>
<category android:name="android.intent.category.CUSTOM_TEST" />
</intent-filter>
</activity>
我找不到对此的解释,因为无法真正找到问题的根源。它只是工作
关于android - 从快捷方式启动 Activity 总是同时启动主 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28228735/