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

Android 桌面快捷方式直連網址:廣播廣播機制實作方案(其二)

編輯:關於 Android 程式設計

上一篇我們談到,透過啟動 App 再打開網頁的方式來實現桌面快捷連結,做法雖然簡單,但使用體驗上總是差了那麼一點意思——使用者還得先經過 App 這一層,顯得多此一舉。

這篇文章要帶大家換個思路,借助 Android 的 Broadcast 廣播機制來完成同樣的事情。這套做法不僅效果更貼近原生體驗,最大的優勢在於:不必再依賴任何 App 作為中介,就能直接從桌面圖標跳轉到指定網址。

具體實作步驟如下:

一、宣告必要權限

首先在 AndroidManifest.xml 中加入讀取設定與安裝捷徑的權限:

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

二、發送安裝捷徑的廣播

接著在 MainActivity 的 onCreate 方法中,設定並發送對應的廣播 Intent:

final Intent shortCutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
final Parcelable icon = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap();
// 取得快捷方式的圖示
Uri uri = Uri.parse("https://blog.csdn.net/wanggsx918");
Intent pendingIntent = new Intent(Intent.ACTION_VIEW, uri);
// 桌面快捷方式圖標
shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
// 桌面快捷方式標題
shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
// 桌面快捷方式動作:點擊圖標時執行的行為
shortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, pendingIntent);
context.sendBroadcast(shortCutIntent);

沒錯,就是這麼乾淨俐落。透過廣播向 Launcher 發送 INSTALL_SHORTCUT 動作,就能在桌面上生成一個直接指向網址的捷徑,既正統又完整,正是我們想要的效果。

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