一、聲明權限:
在AndroidManifest.xml 文件中聲明 建立和刪除快捷方式時聲明權限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
注:因爲MOTO的部分機型還要加上如下權限,下面的兩個也要加上去
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
二、判斷是否有快捷方式
/**
* 是否已建立快捷方式
* @return
*/
private boolean hasShortcut()
{
boolean isInstallShortcut = false;
final String AUTHORITY ="com.android.launcher.settings";
final Uri CONTENT_URI = Uri.parse("content://" +AUTHORITY + "/favorites?notify=true");
Cursor c = getContentResolver().query(CONTENT_URI, new String[] {"title", "iconResource" }, "title=?", new String[] {getString(R.string.app_name).trim()}, null);
if(null != c && c.getCount() > 0)
{
isInstallShortcut = true ;
}
return isInstallShortcut;
}
三、建立快捷方式
/**
* 建立快捷方式
*/
private void addShortcut()
{
if (hasShortcut())
{
return;
}
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.getPackageName() + "." +this.getLocalClassName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
//快捷方式的圖標
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
sendBroadcast(shortcut);
}
四、刪除快捷方式:
/**
* 刪除程序的快捷方式
*/
private void delShortcut(){
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
//快捷方式的名稱
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
//指定當前的Activity爲快捷方式啓動的對象: 如 com.everest.video.VideoPlayer
//注意: ComponentName的第二個參數必須是完整的類名(包名+類名),不然沒法刪除快捷方式
String appClass = this.getPackageName() + "." +this.getLocalClassName();
ComponentName comp = new ComponentName(this.getPackageName(), appClass);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
sendBroadcast(shortcut);
}
備註:
若是按照上述方法建立快捷方式的話,在進入程序之後點擊HOME鍵,而後點擊快捷方式之後,又從新啓動了程序,進入歡迎界面。
解決方法:
在建立快捷方式的時候添加如下代碼:
intent.addCategory(Intent.CATEGORY_LAUNCHER);