简体   繁体   中英

Drop a launcher icon on Android home screen (like Google Play does)

I want use my app to drop a launcher icon of a 3rd party app.

I have the INSTALL_SHORTCUT permission:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

I am able to drop the shortcut, however, the icon appears pixelated.

What is the way to get an icon in the size appropriate to the home screen? (like the one Google Play drop after installation)

*I use the following code to get the icon Bitmap for the shortcut:

public static Drawable getInstalledPackageIcon(Context context, String packageName) {

    PackageManager packageManager = context.getPackageManager();

    try {

        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);

        if (applicationInfo != null) {
            Drawable iconDrawable = applicationInfo.loadIcon(packageManager);
            return iconDrawable;
        }

    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    return null;
}

I don't think the solution with the use of getDrawableForDensity is the most correct. You should let the launcher decide, passing the resource name as you can see in this example:

private void createAppShortcut(String packageName) {

    PackageManager packageManager = getPackageManager();

    ApplicationInfo appInfo = null;
    Resources resources = null;

    try {
        appInfo = packageManager.getApplicationInfo(packageName, 0);
        resources = packageManager.getResourcesForApplication(packageName);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return;
    }

    Intent shortcutIntent = packageManager.getLaunchIntentForPackage(packageName);
    CharSequence shortcutName = appInfo.loadLabel(packageManager);

    Intent.ShortcutIconResource shortcutIconResource = new Intent.ShortcutIconResource();
    shortcutIconResource.packageName = packageName;
    shortcutIconResource.resourceName = resources.getResourceName(appInfo.icon);

    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
    shortcut.putExtra("duplicate", false);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIconResource);
    sendBroadcast(shortcut);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM