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

Android 開發實戰:為 APP 創建桌面快捷方式

編輯:關於 Android 程式設計

很多應用首次啟動時會自動在手機桌面生成一個快捷圖標,方便用戶快速進入。本文就來看看如何在 Android 程序中實現這一功能。

效果預覽

所需權限

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

配置 AndroidManifest.xml

為閃屏頁 Activity 添加 intent-filter,指定一個自定義的 action:

 <activity android:name="com.myself.news.activity.GuideActivity" android:label="@string/title_activity_guide" > <intent-filter> <action android:name="com.myself.news.ACTION_HOME" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>

核心代碼

在閃屏頁 Activity 的 onCreate 方法中調用 installShortcut():

 // 創建快捷方式 // com.android.launcher.permission.INSTALL_SHORTCUT private void installShortcut() { // 判斷有沒有創建過快捷方式 boolean isCreated = SharedPreferencesUtils.getBoolean(this, GlobalConstantsUtils.PREF_IS_SHORTCUT_INTALLED, false); // 判斷是否已經創建過 if (!isCreated) { // 發廣播 Intent intent = new Intent(); intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); // 圖標 intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)); // 名稱 intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "手機安全衛士"); // 動作 Intent actionIntent = new Intent(); actionIntent.setAction(GlobalConstantsUtils.ACTION_HOME); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, actionIntent); sendBroadcast(intent); // 標記已經創建過快捷方式,下次不再創建 SharedPreferencesUtils.setBoolean(this, GlobalConstantsUtils.PREF_IS_SHORTCUT_INTALLED, true); } }

常量工具類 GlobalConstantsUtils

 public static final String PREF_IS_SHORTCUT_INTALLED = "is_shortcut_intalled";// 是否已經創建快捷方式 public static final String ACTION_HOME = "com.myself.news.ACTION_HOME";// 跳轉到主頁面的 ACTION

透過發送 INSTALL_SHORTCUT 廣播,並用 SharedPreferences 記錄是否已創建過,就能避免重複生成快捷方式。以上就是本功能的完整實現思路。

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