针对网上的许多快捷方式创建代码的总结,
1.发现创建快捷方式时一定要指定action,否则后续的检查是否已创建和删除快捷键都可能无效
2.有的rom并不会严格升级launcher,所以都检查一遍
3.如果发现点击生成的快捷方式提示未安装应用,那么需要给activity添加IntentFilter,如
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
4.需要添加的权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
<uses-permission android:name="com.android.launcher2.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher3.permission.READ_SETTINGS" />
工具类
public class ShortcutUtil {
/**
* 创建快捷方式
* @param ctx
* @param name 快捷方式名称
* @param iconId 快捷方式图标
* @param target 快捷方式的意图, 记得一定要设置action
*/
public static void createShortCut(Context ctx, String name, int iconId, Intent target){
Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//不允许重复创建
shortcutintent.putExtra("duplicate", false);
//需要现实的名称
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
//快捷图片
Parcelable icon = Intent.ShortcutIconResource.fromContext(ctx, iconId);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//点击快捷图片,运行的程序主入口
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, target);
//发送广播。OK
ctx.sendBroadcast(shortcutintent);
}
// 判读是否已经存在快捷方式
public static boolean isExistShortCut(Context ctx, String name) {
ContentResolver cr = ctx.getContentResolver();
Cursor c = null;
try{
//sdk大于19的时候,launcher3的设置查找
String urlStr = "content://com.android.launcher3.settings/favorites?notify=true";
Uri CONTENT_URI = Uri.parse(urlStr);
c = cr.query(CONTENT_URI, null, "title=?", new String[] { name }, null);
if (c != null && c.getCount() > 0) {
return true;
}
if (c != null) {
c.close();
}
//sdk大于8的时候,launcher2的设置查找
urlStr = "content://com.android.launcher2.settings/favorites?notify=true";
CONTENT_URI = Uri.parse(urlStr);
c = cr.query(CONTENT_URI, null, "title=?", new String[] { name }, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String uri = c.getString(c.getColumnIndex("intent"));
return true;
}
if (c != null) {
c.close();
}
//android.os.Build.VERSION.SDK_INT < 8时
urlStr = "content://com.android.launcher.settings/favorites?notify=true";
CONTENT_URI = Uri.parse(urlStr);
c = cr.query(CONTENT_URI, null, "title=?", new String[] { name }, null);
if (c != null && c.getCount() > 0) {
return true;
}
return false;
}finally {
if(c != null){
c.close();
}
}
}
/**
* 删除快捷方式
* @param ctx
* @param name 快捷方式名称
* @param target 快捷方式的意图, 记得一定要设置action,如果是
*/
public static void deleteShortcut(Context ctx, String name, Intent target) {
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
// 快捷方式名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, target);
ctx.sendBroadcast(shortcut);
}
}