Home » Android » How can I correctly reference the icon file of another app to create a homescreen shortcut

How can I correctly reference the icon file of another app to create a homescreen shortcut

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m working on a app-drawer replacement but I’m having trouble giving the user the ability to create home screen icons.

I can create the shortcuts, but I’m struggling to pull the icons from the respective apps.

I collect information on the apps using:

    manager = getPackageManager();
    apps = new ArrayList<AppDetail>();

    Intent i = new Intent(Intent.ACTION_MAIN, null);
    i.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> availableActivities = manager.queryIntentActivities(i,0);

    Collections.sort(availableActivities, new ResolveInfo.DisplayNameComparator(manager));

    for(ResolveInfo ri:availableActivities){
        AppDetail app = new AppDetail();

        app.name = ri.activityInfo.packageName;

        app.label = ri.loadLabel(manager);
        app.icon = ri.activityInfo.loadIcon(manager);
        app.iconID = ri.getIconResource();
        apps.add(app);

But I’m running into troubles when I try to create the shortcut

        AppDetail selectedApp = apps.get(info.position);

        Intent shortcutIntent = new Intent(this, selectedApp.getClass());
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        final Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, selectedApp.label);

        // the danger zone
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(getBaseContext(),selectedApp.iconID));

        intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

        sendBroadcast(intent);
        finish();

How can I correctly reference the icon file of another app?

Answers:

Please use

Drawable icon = manager.getApplicationIcon(app.name);

to obtain the icon graphics, and

final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, selectedApp.label);

// this line in your code changed
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon.getBitmap());

intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(intent);