1、在桌面增加应用快捷方式
public void createShortCut() {
// 创建快捷方式的Intent
Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
// 不允许重复创建
shortcutintent.putExtra("duplicate", false);
// 需要现实的名称
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// 快捷图片
Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
// 点击快捷图片,运行的程序主入口
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext(), SplashActivity.class));
// 发送广播。OK
sendBroadcast(shortcutintent);
}
在AndroidManifest.xml中增加权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
2、判断快捷方式是否已经存在
public boolean hasShortcut(Activity activity, String shortcutName) {
String url = "";
url = "content://" + getAuthorityFromPermission(activity, "com.android.launcher.permission.READ_SETTINGS") + "/favorites?notify=true";
ContentResolver resolver = activity.getContentResolver();
Cursor cursor = resolver.query(Uri.parse(url), new String[] { "title", "iconResource" }, "title=?", new String[] { getString(R.string.app_name).trim() }, null);
if (cursor != null && cursor.moveToFirst()) {
cursor.close();
return true;
}
return false;
}
在AndroidManifest.xml中增加权限
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
因为不同的手机厂商可能对
手机系统进行了修改使用原生的
“content://com.android.launcher.settings/favorites?notify=true"
或者
"content://com.android.launcher2.settings/favorites?notify=true"
并不能准确判断 需要通过权限去获取当前手机
provider.authority
private String getAuthorityFromPermission(Context context, String permission) {
if (permission == null)
return null;
List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
if (packs != null) {
for (PackageInfo pack : packs) {
ProviderInfo[] providers = pack.providers;
if (providers != null) {
for (ProviderInfo provider : providers) {
if (permission.equals(provider.readPermission))
return provider.authority;
if (permission.equals(provider.writePermission))
return provider.authority;
}
}
}
}
return null;
}