Android 如何在Launcher桌面创建或者删除快捷图标,见如下代码:
public static void deleteShortcut(String activityName, Context context) {
Intent shortcutIntent = new Intent();
shortcutIntent.setClassName(context.getPackageName(), activityName);
shortcutIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, "test_shortcut");
shortcut.putExtra("duplicate", false); //不允许重复创建
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
//快捷方式的图标
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.icon));
context.sendBroadcast(shortcut);
}
public static void createShortcut(String activityName, Context context) {
Intent shortcutIntent = new Intent();
shortcutIntent.setClassName(context.getPackageName(), activityName);
shortcutIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, test_shortcut);
shortcut.putExtra("duplicate", false); //不允许重复创建
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
//快捷方式的图标
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.icon));
context.sendBroadcast(shortcut);
}
public static boolean hasShortcut(Context context) {
boolean isInstallShortcut = false;
final ContentResolver cr = context.getContentResolver();
final String AUTHORITY = getAuthorityFromPermission(context, "com.android.launcher.permission.READ_SETTINGS");
if (TextUtils.isEmpty(AUTHORITY)) {
return false;
}
final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
Cursor c = cr.query(CONTENT_URI, new String[]{"title", "iconResource"}, "title=?", new String[]{“test_shortcut”}, null);
if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
}
if (c != null) {
c.close();
}
return isInstallShortcut;
}
<pre name="code" class="java"> /**
* android系统桌面的基本信息由一个launcher.db的Sqlite数据库管理,里面有三张表
* 其中一张表就是favorites。这个db文件一般放在data/data/com.android.launcher(launcher2)文件的databases下
* 但是对于不同的rom会放在不同的地方
* 例如MIUI放在data/data/com.miui.home/databases下面
* htc放在data/data/com.htc.launcher/databases下面
* @param context
* @param permission 读取设置的权限 READ_SETTINGS_PERMISSION
* @return
*/
private static String getAuthorityFromPermission(Context context, String permission) {
if (permission == null || permission.length == 0) {
return null;
}
List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
if (packs == null) {
return null;
}
for (PackageInfo pack : packs) {
ProviderInfo[] providers = pack.providers;
if (providers != null) {
for (ProviderInfo provider : providers) {
if (permission.equals(provider.readPermission)|| permission.equals(provider.writePermission)) {
return provider.authority;
}
}
}
}
return null;
}