最近看別人的應用都有自動添加案頭表徵圖的功能,然後就想讓自己的應用也具有這樣的功能,下邊是我練習的時候用的方法代碼,供大家參考。
每個可以互動的應用,在項目資訊清單檔中都有Launcher類,除了提示系統這個Activity是入口函數外,還會在應用列表中添加一個應用的快捷表徵圖。本文講述Launcher通過自己註冊的InstallShortCutReceiver和UnInstallShortCutReceiver實現了捷徑表徵圖的產生與移除過程,分析外部apk實用Intent請求產生捷徑和移除捷徑表徵圖的問題。
添加表徵圖:
Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// 是否可以有多個捷徑的副本,參數如果是true就可以產生多個捷徑,如果是false就不會重複添加
intent.putExtra("duplicate", false);
Intent intent2 = new Intent(Intent.ACTION_MAIN);
intent2.addCategory(Intent.CATEGORY_LAUNCHER);
// 刪除的應用程式的ComponentName,即應用程式套件組合名+activity的名字
intent2.setComponent(new ComponentName(this.getPackageName(), this.getPackageName() + ".Main"));
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this,
R.drawable.icon));
sendBroadcast(intent);
需要添加的許可權:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
刪除表徵圖:
Intent intent = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT" );
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
// 要刪除的應用程式的ComponentName,即應用程式套件組合名+activity的名字
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent()
.setComponent(new ComponentName(info.activityInfo.packageName,
info.activityInfo.name)).setAction("android.intent.action.MAIN"));
sendBroadcast(intent);
添加刪除的許可權:<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>