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

Android 應用如何自動建立桌面快捷方式

編輯:關於 Android 程式設計

在 Android 中建立桌面快捷方式的原理其實很單純:本質上就是發送一個系統廣播,並為這個快捷方式設定好對應的 Intent。透過 com.android.launcher.action.INSTALL_SHORTCUT 這個 Action,就能把指定的應用入口「釘」在使用者的桌面上。

以下是一個可直接參考的實作範例:

package com.xikang.android.slimcoach.utils;

import android.content.Intent;
import android.os.Parcelable;

public class ShortCutUtil {
    public static void initShortCut() {
        Intent addShortCut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 避免重複建立快捷方式
        addShortCut.putExtra("duplicate", false);

        String title = AppXiKang.getApp().getString(R.string.app_name); // 名稱
        Parcelable icon = Intent.ShortcutIconResource.fromContext(AppXiKang.getApp(), R.drawable.icon); // 圖標

        // 點擊快捷方式後要執行的 Intent
        Intent intent = new Intent(AppXiKang.getApp(), AppStart.class);

        // 設定快捷方式的標題、圖標與 Intent
        addShortCut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
        addShortCut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        addShortCut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

        // 發送廣播,完成快捷方式的建立
        AppXiKang.getApp().sendBroadcast(addShortCut);
    }
}

其中 AppXiKang.getApp() 是用來取得應用程式上下文(Context)的方法,你可以依自己的專案結構替換成合適的寫法。

別忘了加上權限

建立快捷方式需要在清單檔(AndroidManifest.xml)中宣告對應權限,否則廣播不會生效:

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

使用時機的建議

比較友善的做法,是在使用者有明確需求時(例如點擊某個「加入桌面」的按鈕),先彈出一個 AlertDialog 提示,等使用者確認後再呼叫建立。這樣既不會打擾使用者,也能讓操作意圖更清晰。

至於市面上有些應用會在安裝完成的當下就直接建立快捷方式,這種做法對使用者並不友善,容易引來反感,因此並不建議採用。

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