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

Android 桌面快捷方式的建立、驗證與刪除(實測可用)

編輯:關於 Android 程式設計

讓使用者在桌面放一個 App 的捷徑,是提升黏著度的小技巧。這件事靠三組不同的權限與三個廣播完成,其中「刪除」的環節最容易踩坑——網路上到處抄來的那份程式碼其實是刪不掉的。以下整理實測可行的完整版本。測試環境為 Android 2.1 以上。

第一步:Manifest 權限配置

建立快捷方式:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

驗證快捷方式是否存在:

<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />

刪除快捷方式:

<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

三個權限分別對應三個動作,缺一個就該功能失效,建議一次補齊。

程式碼

public class ShortCutSample {

    /**
     * 添加快捷方式
     */
    public void creatShortCut(Activity activity, String shortcutName, int resourceId) {
        Intent intent = new Intent();
        intent.setClass(activity, activity.getClass());
        /* 以下兩句是為了在卸載應用的時候同時刪除桌面快捷方式 */
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");

        Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 不允許重複創建
        shortcutintent.putExtra("duplicate", false);
        // 需要顯示的名稱
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
        // 快捷圖片
        Parcelable icon = Intent.ShortcutIconResource.fromContext(
                activity.getApplicationContext(), resourceId);
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        // 點擊快捷圖片,運行的程式主入口
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        // 發送廣播
        activity.sendBroadcast(shortcutintent);
    }

    /**
     * 刪除快捷方式
     */
    public void deleteShortCut(Activity activity, String shortcutName) {
        Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
        // 快捷方式的名稱
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);

        /*
         * 網上看到的基本都是下面這幾句,測試時發現並不能刪除快捷方式。
         * String appClass = activity.getPackageName() + "." + activity.getLocalClassName();
         * ComponentName comp = new ComponentName(activity.getPackageName(), appClass);
         * shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
         *         new Intent(Intent.ACTION_MAIN).setComponent(comp));
         */

        /* 改成以下方式能夠成功刪除,
         * 估計是刪除和創建需要對應才能找到快捷方式並成功刪除 */
        Intent intent = new Intent();
        intent.setClass(activity, activity.getClass());
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        activity.sendBroadcast(shortcut);
    }

    /**
     * 判斷是否存在快捷方式
     */
    public boolean hasShortcut(Activity activity, String shortcutName) {
        String url = "";
        int systemversion = Integer.parseInt(android.os.Build.VERSION.SDK);
        /* 大於 8 的時候在 com.android.launcher2.settings 裡查詢(未測試) */
        if (systemversion < 8) {
            url = "content://com.android.launcher.settings/favorites?notify=true";
        } else {
            url = "content://com.android.launcher2.settings/favorites?notify=true";
        }
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = resolver.query(Uri.parse(url), null, "title=?",
                new String[] { shortcutName }, null);
        if (cursor != null && cursor.moveToFirst()) {
            cursor.close();
            return true;
        }
        return false;
    }
}

為什麼刪除那段要這樣寫

這是最值得記住的一點:刪除時傳入的 Intent 必須與建立時完全一致。系統是靠 EXTRA_SHORTCUT_INTENT 來比對要刪哪一個捷徑的,若建立時用的是 setClass + MAIN + LAUNCHER 的組合,刪除時卻改用 ComponentName 去湊,比對就會失敗,廣播發出去也沒反應。網路上流傳的版本多半栽在這裡。

呼叫測試

public class mainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ShortCutSample sample = new ShortCutSample();
        String shortcutName = getString(R.string.app_name);
        if (sample.hasShortcut(this, shortcutName))
            sample.deleteShortCut(this, shortcutName);
        else
            sample.creatShortCut(this, shortcutName, R.drawable.icon);
    }
}

這段邏輯是「有就刪、沒有就建」,每次啟動都會反轉一次狀態,方便驗證兩個方向都正常。

幾點實務提醒

hasShortcut 的相容性最脆弱。它直接查詢 Launcher 的 ContentProvider,而各家桌面 App( including 各家客製 ROM 的桌面)的 authority 與表結構並不統一,com.android.launcher2.settings 這個值在很多新機型上根本不存在,query 會直接失敗。因此這個方法必須包在 try-catch 裡,並且做好「查不到就當作不存在」的降級處理,否則在部分裝置上會閃退。

duplicate 參數不是萬靈丹。不同 Launcher 對 "duplicate": false 的解讀不完全一致,有些仍會重複建立。比較穩健的做法是自己先用 hasShortcut 判斷,再決定要不要發廣播。

記得關閉 Cursor。範例只在 moveToFirst() 為 true 的分支關了 Cursor,若查無結果就會洩漏,建議用 finally 收尾。

整體來說,桌面捷徑這塊因為高度依賴 Launcher 實作,天生缺乏統一契約,實作時請把「容錯」放在第一位。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved