1. 程式人生 > >Android 新增App快捷方式到桌面

Android 新增App快捷方式到桌面

主要原理是通過向系統傳送建立快捷方式的廣播

  • 設定Intent,傳遞快捷方式的資訊,名字和圖示等
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//快捷方式的名稱  
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getResources().getString(R.string.app_name));//快捷方式的名字
shortcut.putExtra("duplicate", false); //不允許重複建立  

//快捷方式的圖示  
ShortcutIconResource iconRes = ShortcutIconResource.fromContext
(context, R.mipmap.icon); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
  • 用於傳送建立快捷方式的廣播
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(context, context.getClass().getName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
  • 傳送建立快捷方式的廣播
context.sendBroadcast(shortcut);

需要申請許可權,否則建立不了

<!-- 快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

以上簡單幾步,快捷方式建立OK!


歡迎關注我的公眾號,和我一起每天進步一點點!
這裡寫圖片描述