1 回答

TA貢獻2003條經驗 獲得超2個贊
如果您在安裝應用程序自動創建快捷方式后在 Google Play 商店中發布您的應用程序,但如果您想處理 Android 為我們提供了一個意圖類 com.android.launcher.action.INSTALL_SHORTCUT,它可用于向主屏幕添加快捷方式。在下面的代碼片段中,我們創建了一個名為 HelloWorldShortcut 的活動 MainActivity 的快捷方式。
首先,我們需要向 android manifest XML 添加權限 INSTALL_SHORTCUT。
<uses-permission
android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
addShortcut() 方法在主屏幕上創建一個新的快捷方式。
private void addShortcut() {
//Adding shortcut for MainActivity
//on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent
.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.drawable.ic_launcher));
addIntent
.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
addIntent.putExtra("duplicate", false); //may it's already there so don't duplicate
getApplicationContext().sendBroadcast(addIntent);
}
請注意我們如何創建包含目標活動的快捷方式 Intent 對象。此意圖對象作為 EXTRA_SHORTCUT_INTENT 添加到另一個意圖中。
最后,我們廣播新的意圖。這將添加一個快捷方式,其名稱為 EXTRA_SHORTCUT_NAME,圖標由 EXTRA_SHORTCUT_ICON_RESOURCE 定義。
還要放置此代碼以避免多個快捷方式:
if(!getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).getBoolean(Utils.IS_ICON_CREATED, false)){
addShortcut();
getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).edit().putBoolean(Utils.IS_ICON_CREATED, true);
}
添加回答
舉報