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

Android 開發筆記 49:建立與移除桌面捷徑

編輯:關於 Android 程式設計

網上找過一堆寫法,最後發現下面這個版本最穩,主要是加了 duplicate 旗標,不會重複產生捷徑。

建立捷徑

private void addShortcut() {
    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");

    // 捷徑名稱
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
    // 不允許重複建立
    shortcut.putExtra("duplicate", false);

    // 注意:這裡要填程式啟動時的第一個 Activity
    Intent intent = new Intent(this, HomeActivity.class);
    intent.setAction("com.figo.activity.home");

    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

    // 捷徑圖示
    Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

    sendBroadcast(shortcut);
}

移除捷徑

private void delShortcut() {
    Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));

    // 這裡的 intent 必須和建立時完全一致
    Intent intent = new Intent(this, HomeActivity.class);
    intent.setAction("com.figo.activity.home");
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

    sendBroadcast(shortcut);
}

權限宣告

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

Activity 設定

在 AndroidManifest.xml 中,幫啟動用的 Activity 補上 launchMode、orientation、theme 與 intent-filter:

<activity
    android:name="com.figo.activity.HomeActivity"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.NoTitleBar"
    android:windowSoftInputMode="adjustPan" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

幾個實務提醒:移除捷徑時的 Intent 必須與建立時一模一樣(含 action),否則辨識不到;另外部分客製化桌面(尤其是各家自製 launcher)對 INSTALL_SHORTCUT 廣播的反應不一,建議在送出前先判斷是否已存在,避免一次跑出好幾顆圖示。

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