这几天项目需求,要做个快捷方式,然后上网查询了一下,发现现在网上的一些关于快捷方式一些博客都说的比较单一、比较简单、也比较老了,本人就把网上的一些东西,和我自己发现一些东西集成到一起,写个博客出来,以后再写快捷方式,就比较简单一些。从创建快捷方式–>删除快捷方式–>判断快捷方式是否存在–>快捷方式跳转及快捷方式的一些比较蛋疼的问题。
创建快捷方式,网上的都差不多,也比较简单,直接上代码:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);// 加入action,和category之后,程序卸载的时候才会主动将该快捷方式也卸载
intent.setClass(this, "你需要跳转的activity");
intent.putExtra("isGoRecomm", true);
String title = "快捷方式名称"; //快捷方式名称
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
shortcut.putExtra("duplicate", false);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.ccplay_icon_desktop); //快捷方式的图片
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
sendBroadcast(shortcut);
cretaShortcut();
大致就利用两个Intent,第一个Intent来确认快捷方式需要跳转到哪个的页面,第二个Intent通过广播的方式告诉系统,我要创建一个快捷方式。
删除快捷方式:
public static void deleteShortCut(Context context)
{
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,context.getString(R.string.app_name));
/**删除和创建需要对应才能找到快捷方式并成功删除**/
Intent intent = new Intent();
intent.setClass(context, context.getClass());
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,intent);
context.sendBroadcast(shortcut);
}
删除快捷方式和创建快捷方式差不多,也是通过广播的方式,然而使用过的人会发现然并卵。根本不能删除掉,为什么会这样呢?等会再说,我们先继续往下说。
判断快捷方式是否在:
public static boolean hasShortCut(Context context) {
String url = "";
System.out.println(getSystemVersion());
//这是说当前Android系统的版本号时多少:
if(getSystemVersion() < 8){
url = "content://com.android.launcher.settings/favorites?notify=true";
}else{
url = "content://com.android.launcher2.settings/favorites?notify=true";
}
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(Uri.parse(url), null, "title=?",
new String[] {context.getString(R.string.app_name)}, null);
if (cursor != null && cursor.moveToFirst()) {