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

Android 桌面捷徑的建立與刪除實作

編輯:關於 Android 程式設計

想讓使用者在桌面一鍵進入 App 的某個特定頁面?可以透過系統廣播要求 Launcher 建立捷徑,反過來也能要求它移除。

建立捷徑

送出 com.android.launcher.action.INSTALL_SHORTCUT 廣播,並附上名稱、圖示與目標 Intent。這裡的 Intent 指向 WebViewActivity,並把網址等參數一併帶過去,做到「點捷徑直接開指定網頁」的效果。

 /**
* 創建快捷方式
*
* @param map 快捷方式圖標
* @param appName 快捷方式標題
* @param appUrl 快捷方式打開的地址
* @param iconUrl 快捷方式圖標地址
*/
public static void createShortcut(Context activity, Bitmap map, String appName,
String appUrl, String iconUrl){

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

shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
shortcut.putExtra("duplicate", false);// 設置是否重復創建

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
// intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setClass(activity, WebViewActivity.class);// 設置第一個頁面

intent.putExtra("keyword", appUrl);
intent.putExtra("appName", appName);
intent.putExtra("iconUrl", iconUrl);

shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, map);

activity.sendBroadcast(shortcut);
}

刪除捷徑

刪除時送出 UNINSTALL_SHORTCUT 廣播,關鍵是 Intent 中的 className 必須與建立時完全一致,系統才能對上同一個捷徑。

 /**
* 刪除快捷方式
*
* @param shortcutName app 名字
* @param className 絕對路徑如:getPackageName() + ".WebViewActivity"
*/
public static void removeShortcut(Context cxt, String shortcutName, String className) {
Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
shortcutIntent.setClassName(cxt, className);

Intent intent = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);

cxt.sendBroadcast(intent);
}

實務上的限制

各家 Launcher(包括各家客製化桌面)對這兩個廣播的支援程度不一,部分廠商已限制第三方 App 建立捷徑,因此務必把這當成「加分功能」而非核心依賴。另外,EXTRA_SHORTCUT_ICON 直接傳 Bitmap 在跨程序時有大小限制,建議改用 EXTRA_SHORTCUT_ICON_RESOURCE 傳遞資源,會更穩定。

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