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

Android 桌面快捷方式全攻略:從 Launcher3 資料庫看增刪改查與相容性

編輯:關於 Android 程式設計

為什麼快捷方式這麼麻煩

為了讓使用者更快開啟應用,App 常需要在桌面產生一顆快捷方式。如果面前只有原生桌面,這件事很簡單——呼叫系統 API 就好。但現實是各家廠商深度客製、第三方桌面琳瑯滿目,於是相容性問題層出不窮:有的桌面不給刪(小米)、有的不給建(錘子)、有的圖標不給更新(華為榮耀 6);升級降級之後快捷方式變成應用主圖標、點了沒反應、卸載後殘留……

本文討論的範圍限定在「應用桌面快捷方式」,不含長按弹出的動態捷徑。所有快捷方式資訊都存在 Launcher 的 favorite 表裡,實務上最常用的欄位是 _id、title、intent、iconResource、icon,分別代表名稱、啟動意圖、本地圖標與二進位圖標資料。

資料可透過 SQLite Editor 檢視,前提是裝置已 root。

建立快捷方式

在 AndroidManifest.xml 加上安裝快捷方式的權限,並依 Intent 是隱式或顯式,在目標 Activity 上補齊對應的 intent-filter。

刪除快捷方式

同樣需要對應權限,然後送出刪除意圖。

更新快捷方式圖標

系統並沒有提供修改桌面快捷方式的公開 API,只能繞路。其中一條可行路線是直接透過 ContentProvider 改寫資料庫。

有人會問:先刪再建不就得了?確實可以,但部分系統根本不允許刪除;而且建立與刪除都靠廣播,兩者之間還得控制時間間隔,容易出現狀態錯亂。權衡之後,直接改資料是相對穩妥的做法。

/**
 * 更新桌面快捷方式圖標。並非所有機型都有效;若快捷方式不存在則不處理。
 */
public static void updateShortcutIcon(Context context, String title,
                                      Intent intent, Bitmap bitmap) {
    if (bitmap == null) {
        XLog.i(TAG, "update shortcut icon, bitmap empty");
        return;
    }
    try {
        final ContentResolver cr = context.getContentResolver();
        StringBuilder uriStr = new StringBuilder();
        String urlTemp;

        String authority = LauncherUtil.getAuthorityFromPermissionDefault(context);
        if (authority == null || authority.trim().equals("")) {
            authority = LauncherUtil.getAuthorityFromPermission(context,
                    LauncherUtil.getCurrentLauncherPackageName(context)
                            + ".permission.READ_SETTINGS");
        }

        uriStr.append("content://");
        if (TextUtils.isEmpty(authority)) {
            int sdkInt = android.os.Build.VERSION.SDK_INT;
            if (sdkInt < 8) {
                uriStr.append("com.android.launcher.settings");       // Android 2.1 及以下
            } else if (sdkInt < 19) {
                uriStr.append("com.android.launcher2.settings");      // Android 4.4 以下
            } else {
                uriStr.append("com.android.launcher3.settings");      // 4.4 及以上
            }
        } else {
            uriStr.append(authority);
        }
        urlTemp = uriStr.toString();
        uriStr.append("/favorites?notify=true");

        Uri uri = Uri.parse(uriStr.toString());
        Cursor c = cr.query(uri, new String[]{"_id", "title", "intent"},
                "title=? and intent=?", new String[]{title, intent.toUri(0)}, null);

        if (c != null && c.getCount() > 0) {
            c.moveToFirst();
            int index = c.getInt(0);

            ContentValues cv = new ContentValues();
            cv.put("icon", flattenBitmap(bitmap));

            Uri uri2 = Uri.parse(urlTemp + "/favorites/" + index + "?notify=true");
            int rows = cr.update(uri2, cv, null, null);
            // 注意:notifyChange 必須用 uri 而非 uri2,這是個坑
            cr.notifyChange(uri, null);
            XLog.i(TAG, "update ok, affected " + rows + " rows, index is " + index);
        } else {
            XLog.i(TAG, "update result failed");
        }

        if (c != null && !c.isClosed()) {
            c.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        XLog.i(TAG, "update shortcut icon error: " + ex.getMessage());
    }
}

private static byte[] flattenBitmap(Bitmap bitmap) {
    // 粗略估算序列化後的空間,避免寫入過程中的多餘配置與複製
    int size = bitmap.getWidth() * bitmap.getHeight() * 4;
    ByteArrayOutputStream out = new ByteArrayOutputStream(size);
    try {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
        return out.toByteArray();
    } catch (IOException e) {
        XLog.w(TAG, "Could not write icon");
        return null;
    }
}

判斷快捷方式是否已存在

雖然靠 SharedPreferences 記錄、加上 shortcutIntent.putExtra("duplicate", false) 已能避免重複建立,但為求保險,直接查資料庫才是最後一道防線。

/**
 * 檢查快捷方式是否存在(依名稱)。
 * 注意:部分機型無法判定,因此建立時仍建議加上 duplicate=false。
 */
public static boolean isShortCutExist(Context context, String title) {
    boolean result = false;
    try {
        final ContentResolver cr = context.getContentResolver();
        StringBuilder uriStr = new StringBuilder();

        String authority = LauncherUtil.getAuthorityFromPermissionDefault(context);
        if (authority == null || authority.trim().equals("")) {
            authority = LauncherUtil.getAuthorityFromPermission(context,
                    LauncherUtil.getCurrentLauncherPackageName(context)
                            + ".permission.READ_SETTINGS");
        }

        uriStr.append("content://");
        if (TextUtils.isEmpty(authority)) {
            int sdkInt = android.os.Build.VERSION.SDK_INT;
            if (sdkInt < 8) {
                uriStr.append("com.android.launcher.settings");
            } else if (sdkInt < 19) {
                uriStr.append("com.android.launcher2.settings");
            } else {
                uriStr.append("com.android.launcher3.settings");
            }
        } else {
            uriStr.append(authority);
        }
        uriStr.append("/favorites?notify=true");

        Uri uri = Uri.parse(uriStr.toString());
        Cursor c = cr.query(uri, new String[]{"title"}, "title=?",
                new String[]{title}, null);
        if (c != null && c.getCount() > 0) {
            result = true;
        }
        if (c != null && !c.isClosed()) {
            c.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        result = false;
    }
    return result;
}

若同時比對名稱與 Intent 会更精準,因為不同應用可能產生同名快捷方式:

public static boolean isShortCutExist(Context context, String title, Intent intent) {
    boolean result = false;
    try {
        final ContentResolver cr = context.getContentResolver();
        StringBuilder uriStr = new StringBuilder();

        String authority = LauncherUtil.getAuthorityFromPermissionDefault(context);
        if (authority == null || authority.trim().equals("")) {
            authority = LauncherUtil.getAuthorityFromPermission(context,
                    LauncherUtil.getCurrentLauncherPackageName(context)
                            + ".permission.READ_SETTINGS");
        }

        uriStr.append("content://");
        if (TextUtils.isEmpty(authority)) {
            int sdkInt = android.os.Build.VERSION.SDK_INT;
            if (sdkInt < 8) {
                uriStr.append("com.android.launcher.settings");
            } else if (sdkInt < 19) {
                uriStr.append("com.android.launcher2.settings");
            } else {
                uriStr.append("com.android.launcher3.settings");
            }
        } else {
            uriStr.append(authority);
        }
        uriStr.append("/favorites?notify=true");

        Uri uri = Uri.parse(uriStr.toString());
        Cursor c = cr.query(uri, new String[]{"title", "intent"},
                "title=? and intent=?", new String[]{title, intent.toUri(0)}, null);
        if (c != null && c.getCount() > 0) {
            result = true;
        }
        if (c != null && !c.isClosed()) {
            c.close();
        }
    } catch (Exception ex) {
        result = false;
        ex.printStackTrace();
    }
    return result;
}

需要留意的是,桌面分兩類:系統桌面(ROM 自帶)與第三方桌面。一般只需考慮前者;第三方桌面若沒有實作系統回應機制(例如 GO 桌面),是無法判斷的。

相容性守則

最重要的一條:已上線版本的快捷方式 Intent 絕對不要改參數,否則升級或降級時舊快捷方式立刻失效。同時盡量採用隱式呼叫、自訂 CATEGORY,而不要自訂 ACTION,且 Action 必須是 ACTION_MAIN,否則部分機型卸載時無法刪除快捷方式。

必踩的坑(與其解法)

  • 【所有機型】Activity 路徑變更導致舊快捷方式失效
    → 一旦確定包路徑就不要再改;已發布的版本為相容性必須沿用舊方式,新版本也盡量不變更呼叫方式,否則使用者降級後舊快捷方式會失效。
  • 【部分機型】多個快捷方式指向同一 Activity,升級後圖標變成應用圖標(如三星 SII)
    → 盡量避免一對多,可改為各自獨立的 Activity 再轉跳。
  • 【部分機型】卸載後無法刪除快捷方式
    → 與桌面 Launcher 的實作有關。為相容所有 Launcher,Action 請固定使用 Intent.ACTION_MAIN;隱式呼叫則自訂 CATEGORY。
  • 【部分機型】升級時想刪除舊版部分快捷方式卻刪不掉
    → 目前無解。
  • 【部分機型】第三方桌面無法建立、刪除或更新快捷方式
    → 建立大致沒問題,刪除與更新則多數會失敗。盡量避開這些操作,或針對該桌面單獨適配(成本偏高)。
  • 【部分機型】圖標無法即時更新,需重啟
    → 無解。試過重啟 Launcher,結果反而讓原本的快捷方式全部消失;只能重啟手機。理論上應該存在觸發 Launcher 刷新的方式。

標註中的【所有】表示必定出現,【部分】表示部分機型出現。這些限制多源自系統本身,因此實務上的策略是:把兼容成本花在「建立」與「啟動」這兩個必然路徑上,把「刪除」與「更新」當成盡力而為的加分項。

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