create shortcut for thrid-party app, is that possible?

≯℡__Kan透↙ 提交于 2019-12-12 03:45:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!