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

Android 編程實現向桌面添加快捷方式的兩種方法

編輯:關於 Android 程式設計

本文講解 Android 編程實現向桌面添加快捷方式的兩種方法,分享給大家參考。

有時候為了使用方便,需要在桌面上添加快捷方式,下面介紹兩種做法。

方法一

 void setshortCut() { Intent addShortcut = new Intent(); //設置快捷方式的名字 addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式練習"); //構建快捷方式中專門的圖標 Parcelable icon = Intent.ShortcutIconResource.fromContext( ShortcutTest.this, R.drawable.icon); //添加快捷方式圖標 addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); //構建快捷方式執行的 Intent Intent mailto = new Intent(this, ShortcutTest.class); //添加快捷方式 Intent addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, mailto); //正常 setResult(RESULT_OK, addShortcut); } 

通過以上代碼添加的快捷方式,只能在程序啟動中添加,不能加入到事件中,目前我也沒完全想明白原因,知道的朋友歡迎告知。並且這樣添加時不直接加到桌面,而是添加到「添加快捷方式」的窗口中,如圖:

方法二

 private void addShortcut(){ Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); //快捷方式的名稱 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); // shortcut.putExtra("duplicate", false); //不允許重復創建 //指定當前的 Activity 為快捷方式啟動的對象: 如 com.everest.video.VideoPlayer //注意: ComponentName 的第二個參數必須加上點號(.),否則快捷方式無法啟動相應程序 // ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName()); // shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp)); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,ShortcutTest.class)); //快捷方式的圖標 ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); sendBroadcast(shortcut); } 

其中:

 shortcut.putExtra("duplicate", false); 

表示不允許重復設置。這種代碼會直接添加到桌面,並且在圖所示的地方顯示,但需要添加以下權限:

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

更多關於 Android Manifest 權限控制,可參考本站在線工具「Android Manifest 功能與權限描述大全」。希望本文對你的 Android 程序設計有所幫助。

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