Skip to content Skip to sidebar Skip to footer

Create Shortcut For Thrid-party App, Is That Possible?

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)? Int

Solution 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;
}

Post a Comment for "Create Shortcut For Thrid-party App, Is That Possible?"