<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
验证快捷方式是否存在权限:
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
删除快捷方式权限:
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
// 添加快捷方式
public static void addSelfShortCut(Context context) {
Intent thisIntent = new Intent(context, SplashAct.class);
thisIntent.setAction(android.content.Intent.ACTION_MAIN);
thisIntent.addCategory(Intent.CATEGORY_LAUNCHER); //这个很重要,不然会出现启动两个应用
thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
// 快捷方式的名称
Intent shortcut = new Intent(CREATE_SHORTCUT_ACTION);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
shortcut.putExtra("duplicate", false);
// 快捷方式的图标
Parcelable icon = Intent.ShortcutIconResource.fromContext(context, R.drawable.icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, thisIntent);
context.sendBroadcast(shortcut);
}
/**
* 删除快捷方式
* */
public void deleteShortCut(Activity activity,String shortcutName)
{
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,shortcutName);
//在网上看到到的基本都是一下几句,测试的时候发现并不能删除快捷方式。
//String appClass = activity.getPackageName()+"."+ activity.getLocalClassName();
//ComponentName comp = new ComponentName( activity.getPackageName(), appClass);
//shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
/**改成以下方式能够成功删除,估计是删除和创建需要对应才能找到快捷方式并成功删除**/
Intent intent = new Intent();
intent.setClass(activity, activity.getClass());
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,intent);
activity.sendBroadcast(shortcut);
}
/**
* 判断是否存在快捷方式
* */
public boolean hasShortcut(Activity activity,String shortcutName)
{
String url = "";
int systemversion = Integer.parseInt(android.os.Build.VERSION.SDK);
/*大于8的时候在com.android.launcher2.settings 里查询(未测试)*/
if(systemversion < 8){
url = "content://com.android.launcher.settings/favorites?notify=true";
}else{
url = "content://com.android.launcher2.settings/favorites?notify=true";
}
ContentResolver resolver = activity.getContentResolver();
Cursor cursor = resolver.query(Uri.parse(url), null, "title=?",new String[] {shortcutName}, null);
if (cursor != null && cursor.moveToFirst()) {
cursor.close();
return true;
}
return false;
}