背景
在Android设备上,为某个应用创建一个特定的快捷方式,可以快速进入应用的某个操作,比如浏览器将某个页面收藏到桌面,点击桌面的快捷方式直接打开页面。
代码实现
添加桌面图标快捷方式代码非常简单,在API 26(Android O)以下的版本,并没有提供API进行创建桌面快捷方式,但是用户可以通过广播的方式创建桌面快捷方式。在API 26(Android O)及以上版本的系统,对开发者开放了快捷方式的相关API,可以调用API直接创建快捷方式。
其实发送广播的方式创建快捷方式,是发送一个广播给桌面应用Launcher接收,Launcher收到广播后创建应用。
实现代码
/**
* 添加桌面图标快捷方式
* @param activity Activity对象
* @param name 快捷方式名称
* @param icon 快捷方式图标
* @param actionIntent 快捷方式图标点击动作
*/
public void addShortcut(Activity activity, String name, Bitmap icon, Intent actionIntent) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// 创建快捷方式的intent广播
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
// 添加快捷名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
// 快捷图标是允许重复(不一定有效)
shortcut.putExtra("duplicate", false);
// 快捷图标
// 使用资源id方式
// Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(activity, R.mipmap.icon);
// shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
// 使用Bitmap对象模式
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
// 添加携带的下次启动要用的Intent信息
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, actionIntent);
// 发送广播
activity.sendBroadcast(shortcut);
} else {
ShortcutManager shortcutManager = (ShortcutManager) activity.getSystemService(Context.SHORTCUT_SERVICE);
if (null == shortcutManager) {
// 创建快捷方式失败
Log.e("MainActivity", "Create shortcut failed");
return;
}
ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(activity, name)
.setShortLabel(name)
.setIcon(Icon.createWithBitmap(icon))
.setIntent(actionIntent)
.setLongLabel(name)
.build();
shortcutManager.requestPinShortcut(shortcutInfo, PendingIntent.getActivity(activity,
RC_CREATE_SHORTCUT, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT).getIntentSender());
}
}
配置权限
实现创建桌面快捷方式的功能,还需要在AndroidManifest.xml中配置权限,配置的权限是与Launcher的相关权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
注意:使用较高版本的buildTool的时候,在AndroidManifest.xml中配置权限的时候,能投提示有两个关于快捷方式的两个权限(安装和卸载),但是在低版本系统中会无效。
<uses-permission android:name="android.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.UNINSTALL_SHORTCUT" />
根据查看API文档发现,这两个权限是在API 19才加进去的,再看看对应的值,其实和上面配置的是一样的,`android.permission.INSTALL_SHORTCUT`对应的值是`com.android.launcher.permission.INSTALL_SHORTCUT`,`android.permission.UNINSTALL_SHORTCAT`对应的值是`com.android.launcher.permission.UNINSTALL_SHORTCUT`,所以在AndroidManifest.xml中配置对应的值才能正常工作,为了兼容性,建议同时将这四个都加进去。
存在问题
创建桌面快捷方式在碎片化的Android设备上,也不一定可以成功,特别是前一种使用广播的方式进行创建,在某些深度定制的ROM上容易出现失败,后一种方式没有经过验证,大家有条件可以对比一下。