有時候爲了使用方便,需要在桌面上添加快捷方式,下面是兩種添加快捷方式的方法:
1.代碼
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);
}
通過以上代碼添加的快捷方式,只能在程序啓動中添加,不能加入到事件中,現在也沒有想明白是什麼,也沒有仔細研究一下,希望知道的朋友通知一下!並且這樣添加的時候,不直接添加到桌面中,而是添加到添加快捷方式窗口中,如圖:
2.
代碼
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" />