先判断有木有这个快捷方式:
// 判读是否已经存在快捷方式 public boolean isExistShortCut() { boolean isInstallShortcut = false; final ContentResolver cr = Main3Activity.this.getContentResolver(); // 2.2系统之后是”com.android.launcher2.settings”,之前的为"com.android.launcher.settings" final String AUTHORITY = "com.android.launcher2.settings"; final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); Cursor c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { getString(R.string.app_name) }, null); if (c != null && c.getCount() > 0) { isInstallShortcut = true; System.out.println("已经存在快捷方式"); } return isInstallShortcut; }
/** * 判断桌面是否已添加快捷方式 */ private static boolean hasShortcut(Context cx) { boolean result = false; // 获取当前应用名称 // String title = null; // try { // final PackageManager pm = cx.getPackageManager(); // title = pm.getApplicationLabel( // pm.getApplicationInfo(cx.getPackageName(), // PackageManager.GET_META_DATA)).toString(); // } catch (Exception ignored) { // } final String uriStr; if (android.os.Build.VERSION.SDK_INT < 8) { uriStr = "content://com.android.launcher.settings/favorites?notify=true"; } else { uriStr = "content://com.android.launcher2.settings/favorites?notify=true"; } final Uri CONTENT_URI = Uri.parse(uriStr); final Cursor c = cx.getContentResolver().query(CONTENT_URI, null, "title=?", new String[]{cx.getString(R.string.app_name)}, null); if (c != null && c.getCount() > 0) { result = true; } return result; }
AndroidManifast.xml加入权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/> <!-- 快捷方式信息需要从setting中读取 --> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
在onCreate()中加入:
if(!isExistShortCut()){ //String title=getResources().getString(R.string.title); Intent addIntent=new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); Parcelable icon=Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher); //获取快捷键的图标 Intent myIntent=new Intent(this, MainActivity.class); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));//快捷方式的标题 addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);//快捷方式的图标 addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);//快捷方式的动作 addIntent.putExtra("duplicate",false); sendBroadcast(addIntent);//发送广播 }