问题
I use code below to create shortcut for my own app, and I wonder if I can create a shortcut for third-party app? If that's possible, Where could I get the icon(Parcelable)?
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcut.putExtra("duplicate", false);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent().setComponent(new ComponentName(className, activity)));
context.sendBroadcast(shortcut);
回答1:
public static void createShortcutForPackage(Context context, String packageName, String className) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, className));
PackageManager pm = context.getPackageManager();
ResolveInfo ri = pm.resolveActivity(intent, 0);
String shortcutName = ri.loadLabel(pm).toString();
String activityName = ri.activityInfo.name;
int iconId = ri.activityInfo.applicationInfo.icon;
Context pkgContext = PackageUtil.createPackageContext(context, packageName);
if (pkgContext != null) {
ShortcutIconResource sir = Intent.ShortcutIconResource.fromContext(pkgContext, iconId);
installShortcut(pkgContext, packageName, activityName, shortcutName, sir);
}
}
public static void installShortcut(Context context, String packageName, String componentName, String shortcutName, Parcelable icon) {
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
ComponentName cn = new ComponentName(packageName, componentName);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(cn));
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
shortcut.putExtra("duplicate", false);
context.sendBroadcast(shortcut);
}
public static Context createPackageContext(Context context, String pkgName) {
Context result = null;
try {
result = context.createPackageContext(pkgName, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
} catch (NameNotFoundException e) {
Log.d(TAG, "createPackageContext(): " + e.getStackTrace());
}
return result;
}
来源:https://stackoverflow.com/questions/17339231/create-shortcut-for-thrid-party-app-is-that-possible