网上一搜一大把为自己的应用创建快捷方式,但是本文的侧重点在为“
指定的应用”创建桌面快捷方式。
常见的桌面快捷方式有两要素:1.应用名 2.应用图标。
指定应用图标的信息是:
-
- ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(pkgContext,
- iconIdentifier);
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
创建第三方应用的快捷方式关键在于如何获取第三方应用的上下文环境,关键代码为:
- Context pkgContext = context.createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY
- | Context.CONTEXT_INCLUDE_CODE);
OK,基础知识讲完了,下面直接给代码以飨读者。
-
-
-
-
-
-
-
-
- public boolean addShortcut(Context context, String pkg) {
-
- String title = "unknown";
-
- String mainAct = null;
-
- int iconIdentifier = 0;
-
- PackageManager pkgMag = context.getPackageManager();
- Intent queryIntent = new Intent(Intent.ACTION_MAIN, null);
- queryIntent.addCategory(Intent.CATEGORY_LAUNCHER);
- List<ResolveInfo> list = pkgMag.queryIntentActivities(queryIntent,
- PackageManager.GET_ACTIVITIES);
- for (int i = 0; i < list.size(); i++) {
- ResolveInfo info = list.get(i);
- if (info.activityInfo.packageName.equals(pkg)) {
- title = info.loadLabel(pkgMag).toString();
- mainAct = info.activityInfo.name;
- iconIdentifier = info.activityInfo.applicationInfo.icon;
- break;
- }
- }
- if (mainAct == null) {
-
- return false;
- }
- Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
-
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
-
-
- ComponentName comp = new ComponentName(pkg, mainAct);
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
- new Intent(Intent.ACTION_MAIN).setComponent(comp));
-
- Context pkgContext = null;
- if (context.getPackageName().equals(pkg)) {
- pkgContext = context;
- } else {
-
- try {
- pkgContext = context.createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY
- | Context.CONTEXT_INCLUDE_CODE);
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- }
- if (pkgContext != null) {
- ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(pkgContext,
- iconIdentifier);
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
- }
-
-
-
- context.sendBroadcast(shortcut);
- return true;
- }