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

Android 中創建桌面快捷方式的代碼實例

編輯:關於 Android 程式設計

為應用在桌面創建快捷方式,可以通過發送廣播的方式來實現。下面分步說明。

一、添加權限(必須)

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

二、添加快捷方式

public static void setupShortcut(Activity activity) {
    // 指向啟動首頁(launcher Activity)
    Intent shortcutIntent = new Intent(activity, MainActivity.class);

    Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    // 快捷方式名稱可任意,不過最好為 app 名稱
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "hello");
    Parcelable iconResource =
            Intent.ShortcutIconResource.fromContext(activity, R.drawable.ic_launcher);
    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
    // 不允許重復創建
    intent.putExtra("duplicate", false);

    // 發送廣播創建快捷方式
    activity.sendBroadcast(intent);
}

三、指向非 Launcher Activity

快捷方式也可以指向其他 Activity,只需在 AndroidManifest 中對應的 Activity 裡添加如下配置:

<intent-filter>
    <action android:name="android.intent.action.CREATE_SHORTCUT" />
</intent-filter>

例如把上面的 MainActivity 換成任意其他 Activity,同時在清單中為它添加上述 intent-filter 即可。

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