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

Android 如何動態創建桌面快捷方式

編輯:關於 Android 程式設計

桌面快捷方式本質上就是一個「程序入口」,安裝完成後系統自動生成的那個圖標就是最典型的例子。不過很多場景需要更進一步:像 QQ 會話那樣,為某個好友或某條數據動態生成名稱與圖標都不同的快捷方式。本文把完整流程梳理一遍。

第一步:聲明權限

沒有這個權限,後面的廣播會被系統直接忽略:

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

第二步:在清單文件中配置目標 Activity

<activity android:name="com.easemob.chatuidemo.activity.ChatActivity" >
    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
        <action android:name="android.intent.action.CREATE_SHORTCUT" />
    </intent-filter>
</activity>

這裡配置的 ChatActivity,就是點擊快捷方式後要跳轉到的目標頁面。

第三步:發送安裝廣播

public void CreateShotCut(final Context context, final Class<?> clazz,
                          final String name, final String userId) {
    Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
    // 加上這兩個屬性,卸載應用時桌面圖標才會被一併清除
    shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    shortcutIntent.setClass(context, clazz);

    // 攜帶業務參數,例如會話 ID
    Bundle bundle = new Bundle();
    bundle.putString("userId", userId);
    shortcutIntent.putExtras(bundle);

    shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Intent shortcut = new Intent(Intent.ACTION_CREATE_SHORTCUT);
    shortcut.putExtra("duplicate", false);                              // 不允許重複創建
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);     // 點擊後啟動的 Intent
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);                 // 圖標下方顯示的名稱
    Parcelable icon = Intent.ShortcutIconResource.fromContext(
            getApplicationContext(), R.drawable.ic_launcher);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);        // 圖標資源
    shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    context.sendBroadcast(shortcut);
}

兩個容易踩的坑

第一,不要漏掉 FLAG_ACTIVITY_CLEAR_TOP。缺少這行時,點擊快捷方式往往會直接跳到任務棧頂,而不是指定的 Activity;如果目標 Activity 恰好已在棧頂,系統甚至可能只是複用並銷毀重來,表現非常奇怪。加上這個 flag 之後行為才符合預期。

第二,需要動態網絡圖標時換用另一個 key。ShortcutIconResource 只接受本地資源 ID,如果想使用下載得到的圖片,應改用 Bitmap 版本:

// Intent.EXTRA_SHORTCUT_ICON 對應 Bitmap 對象
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);

先把網絡圖片請求回來並轉成 Bitmap,再傳入即可。

補充一點:部分定制 ROM 的桌面對 INSTALL_SHORTCUT 廣播做了限制,若測試時圖標不出現,可以先確認權限是否申請成功,以及更換設備排除 ROM 差異。若要卸載快捷方式,發送 action 為 UNINSTALL_SHORTCUT 的廣播並攜帶相同 Intent 即可。

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