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

Android 動態添加快捷方式到桌面

編輯:關於 Android 程式設計

想讓使用者一鍵直達某個頁面(例如某家店鋪的詳情頁),可以在執行期動態建立桌面捷徑。整個流程分兩半:先檢查是否已存在,再送出建立廣播。

先檢查重複

Android 的桌面(Launcher)會把捷徑存在自己的 favorites 資料表中,因此可以透過 ContentResolver 直接查詢,用標題當作判斷依據:

/**
 * 是否已建立捷徑
 */
private boolean hasShortcut() {
    boolean isInstallShortcut = false;
    final String AUTHORITY = "com.android.launcher.settings";
    final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
            + "/favorites?notify=true");

    Cursor c = getContentResolver().query(CONTENT_URI,
            new String[] { "title", "iconResource" },
            "title=?", new String[] { shopDetail.getTitle() }, null);

    if (null != c && c.getCount() > 0) {
        isInstallShortcut = true;
    }
    return isInstallShortcut;
}

建立捷徑

/**
 * 建立捷徑
 */
private void addShortcut() {
    if (hasShortcut()) {
        return;   // 已存在就不重複建立
    }

    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");

    // 捷徑名稱
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
            shopDetail.getTitle() + "的店鋪");

    // 不允許重複建立
    shortcut.putExtra("duplicate", false);

    // 指定點擊捷徑時要啟動的目標元件
    ComponentName comp = new ComponentName("com.itel.platform",
            "com.itel.platform" + "." + "ui.shop.ShopIndexActivity");

    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
            new Intent(Intent.ACTION_MAIN)
                    .putExtra("shopId", uShopId)
                    .putExtra("openType", 1)
                    .setComponent(comp));

    // 捷徑圖示:有圖就用圖,沒圖就退回 App 圖示
    if (bitmap != null) {
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
    } else {
        Parcelable icon = Intent.ShortcutIconResource.fromContext(
                this, R.drawable.ic_launcher);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
    }

    // 部分 Android 版本不會顯示提示,這裡手動補一個
    if (Build.VERSION.SDK_INT == 10 || Build.VERSION.SDK_INT >= 19) {
        Toast.makeText(context,
                "快捷鍵 " + shopDetail.getTitle() + "的店鋪 已添加",
                Toast.LENGTH_SHORT).show();
    }

    sendBroadcast(shortcut);
}

幾點要注意的地方

權限。送出建立捷徑的廣播需要 com.android.permission.INSTALL_SHORTCUT,缺少它會靜默失敗,不會拋出例外,因此相當難查。

查詢 URI 並非標準。com.android.launcher.settings 這個 authority 是原生 Launcher 的私有實作,各家客製桌面(包括多數大陸廠商 ROM)未必相同,直接查詢可能拿到空結果或拋出例外。實務上較穩妥的做法是把查詢包在 try-catch 裡,並額外維護一份本地已建立的紀錄(例如存進 SharedPreferences)作為主要判斷依據,把系統查詢當成輔助。

Cursor 別忘了關閉。範例中為了精簡省略了 c.close(),實際撰寫時應在 finally 中確保釋放,或改用 try-with-resources。

新版系統的限制。Android 8.0 之後,這個 INSTALL_SHORTCUT 廣播在部分 Launcher 上已不再受支援,改以 ShortcutManager 的 requestPinShortcut() API 為官方途徑,且需要使用者互動確認。若要支援新版本,兩套做法都得實作。

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