Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

為 App 動態建立桌面捷徑,並在移除時一併清掉圖示

編輯:關於 Android 程式設計

有些 App 會希望在使用者完成某個操作後,於桌面額外放一顆捷徑,直接導向特定頁面。Android 把這件事做成一個廣播:送出帶有 ACTION_ADD_SHORTCUT 的 Intent,由 Launcher 接收並建立圖示。

一、建立桌面圖示

Intent intent = new Intent();
intent.setClass(this, SplashActivity.class);

Intent addShortcut = new Intent(ACTION_ADD_SHORTCUT);
Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);

addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
addShortcut.putExtra("duplicate", 0);
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
sendBroadcast(addShortcut);

幾個參數的意義:EXTRA_SHORTCUT_NAME 是桌面上顯示的名稱,EXTRA_SHORTCUT_INTENT 是點下去要啟動的目標,EXTRA_SHORTCUT_ICON_RESOURCE 指定圖示資源,而 duplicate 設為 0 表示不要建立重複的圖示。

二、補上 MAIN / LAUNCHER 這兩個 filter

作為捷徑目標的 Intent 必須具備下面這組 action 與 category,Launcher 才認得它是一個啟動入口:

intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");

少了這兩行,圖示可能會建立成功,但點下去卻沒有對應的 Activity 可以啟動。實務上更嚴謹的做法是直接寫成常數 Intent.ACTION_MAIN 與 Intent.CATEGORY_LAUNCHER,避免字串打錯。

三、完整版本

Intent intent = new Intent();
intent.setClass(this, SplashActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);

Intent addShortcut = new Intent(ACTION_ADD_SHORTCUT);
Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);

addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
addShortcut.putExtra("duplicate", 0);
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
sendBroadcast(addShortcut);

關於「移除時刪除圖示」

需要澄清一個常見誤解:桌面上由使用者自行新增的捷徑,並不會因為 App 被解除安裝而自動消失,而系統也沒有提供一個可靠的「程式移除時刪除捷徑」的公開 API(歷史上曾有 ACTION_UNINSTALL_SHORTCUT 這類約定,但各版本與各家 Launcher 的支援程度不一,不能依賴)。因此比較務實的處理方式是:

  • 在 App 內提供「移除桌面圖示」的入口,由使用者主動觸發對應的刪除廣播。
  • 若一定要在解除安裝後清理,只能改走 android.intent.action.PACKAGE_REMOVED 這類由系統發送的廣播,並搭配 BOOT_COMPLETED 之外的自訂 receiver 註冊——但這條路仍受各家 ROM 限制,實作前務必在目標機型上實測。
  • 不要假設圖示一定存在。每次操作前先確認狀態,避免重複建立。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved