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

Android 動態創建桌面快捷方式的方法

編輯:Android 程式設計入門

在 Android 中,可以通過發送廣播的方式為應用創建桌面快捷方式。首先需要判斷快捷方式是否已存在,避免重複創建:

// 判讀是否已經存在快捷方式 public boolean isExistShortCut() { boolean isInstallShortcut = false; final ContentResolver cr = Main3Activity.this.getContentResolver(); // 2.2系統之後是"com.android.launcher2.settings",之前的為"com.android.launcher.settings" final String AUTHORITY = "com.android.launcher2.settings"; final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { getString(R.string.app_name) }, null); if (c != null && c.getCount() > 0) { isInstallShortcut = true; System.out.println("已經存在快捷方式"); } return isInstallShortcut; }

接著需要在 AndroidManifest.xml 中加入相應權限:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/> <!-- 快捷方式信息需要從setting中讀取 --> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>

最後在 onCreate() 中加入創建邏輯:

if(!isExistShortCut()){ Intent addIntent=new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); Parcelable icon=Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher); //獲取快捷鍵的圖標 Intent myIntent=new Intent(this, MainActivity.class); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));//快捷方式的標題 addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);//快捷方式的圖標 addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);//快捷方式的動作 addIntent.putExtra("duplicate",false); sendBroadcast(addIntent);//發送廣播 }

通過以上步驟,即可在用戶桌面動態創建應用的快捷方式圖標。

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