一.概述
Android 快捷方式是桌面最基本的组件。它用于直接启动某一应用程序的某个组件。先给大家看看添加,检查,删除快捷方式的整个过程的效果图:
上面出现了两个应用程序的图标,这是开发工具的一个Bug,因为我用的是最新的Android Studio,可能不稳定的原因,不影响我们的实验,其中只有一个可以点击,点击另一个会出异常
二.实现
下面看看怎么实现:
/**
* 添加快捷方式
*/
private void addShortCut() {
//指定动作
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// 不允许重复
shortcut.putExtra("duplicate", false);
// 设置快捷方式的图标
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
// 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
Intent respondIntent = new Intent(this, this.getClass());
//指定动作
respondIntent.setAction(Intent.ACTION_MAIN);
respondIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
respondIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, respondIntent);
sendBroadcast(shortcut);
}
创建快捷方式需要权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
然后我们看看怎样判断快捷方式是否存在:
由于在Android2.2及其以后的版本中,查询快捷方式是否存在的authorities发生了改变,所以我们要进行一下判断,代码如下:
public boolean hasShortCut(Context context) {
String url = "";
System.out.println(getSystemVersion());
if (getSystemVersion() < 8) {
//2.2版本之前
url = "content://com.android.launcher.settings/favorites?notify=true";
} else {
//2.2版本之后
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()) {
cursor.close();
return true;
}
return false;
}
/**
*
* @return 当前系统的Android版本
*/
public int getSystemVersion(){
return Build.VERSION.SDK_INT;
}
查询快捷方式需要权限:
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
下面在看怎么移除快捷方式:
/**
* 移除快捷方式
* @param view
*/
public void delete() {
//指定动作
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
Intent respondIntent = new Intent(this, this.getClass());
//指定动作
respondIntent.setAction(Intent.ACTION_MAIN);
respondIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, respondIntent);
sendBroadcast(shortcut);
}
移除快捷方式需要权限:
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />