Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

拆解 Android 桌面捷徑的建立原理與實作

編輯:初階開發

應用程式想在桌面(Launcher)上放一個自己的捷徑圖示,其實是靠一套廣播溝通機制完成的。

原理:Launcher 收聽的是哪一個廣播?

Launcher 為了讓其他應用程式能定制自己的快捷圖標,註冊了一個專門接收這類請求的 BroadcastReceiver。因此只要照著它的規格構造出對應的 Intent,裝入定制資訊,最後呼叫 sendBroadcast,就能建立一個捷徑。

先來看看這個接收器的註冊資訊,它位於 Launcher 的 AndroidManifest.xml 中:

<!-- Intent received used to install shortcuts from other applications -->
<receiver
    android:name=".InstallShortcutReceiver"
    android:permission="com.android.launcher.permission.INSTALL_SHORTCUT">

    <intent-filter>
        <action android:name="com.android.launcher.action.INSTALL_SHORTCUT" />
    </intent-filter>
</receiver>

發送廣播的三個條件

  1. 你的應用程式必須先取得 com.android.launcher.permission.INSTALL_SHORTCUT 權限。
  2. 送出的 Intent 其 action 必須設為 com.android.launcher.action.INSTALL_SHORTCUT,這樣廣播才會被 Launcher 的 InstallShortcutReceiver 收到。
  3. 捷徑本身的資訊以附加資訊(extras)的形式放在這個 Intent 物件裡,包含圖示、顯示名稱,以及用來啟動目標元件的 Intent 共三項。透過 putExtra 的各種重載方法,指定對應的鍵值即可塞進 Bundle。

程式範例:建立一個可直接撥號的捷徑

private final String ACTION_ADD_SHORTCUT =
        "com.android.launcher.action.INSTALL_SHORTCUT";

Intent addShortcut = new Intent(ACTION_ADD_SHORTCUT);

String numToDial = "110";
Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.jing);
// numToDial = "119";
// icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.huo);

// 圖示
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

// 名稱
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, numToDial);

// 啟動目標元件的 Intent
Intent directCall = new Intent();
directCall.setData(Uri.parse("tel://" + numToDial));
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, directCall);

sendBroadcast(addShortcut);

三個 extras 的對應關係

  • EXTRA_SHORTCUT_NAME:捷徑在桌面上顯示的文字(字串)。
  • EXTRA_SHORTCUT_ICON_RESOURCE:捷徑圖示,用 ShortcutIconResource 包裝;也可以改用 EXTRA_SHORTCUT_ICON 傳 Bitmap。
  • EXTRA_SHORTCUT_INTENT:點擊捷徑時要啟動的 Intent,決定捷徑實際的行為。

把這三項資訊湊齊,你就能輕而易舉地為應用程式添加快捷圖標——上面這個範例做出來的,就是一個點下去直接撥號的捷徑。

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