문제

I am able to use an intent filter to gather a list of all installed launchers. The trouble is pulling out an int reference to the app icon. The code below catches a NameNotFoundException error.

public RemoteViews getViewAt(int position) {
    PackageManager pm = mContext.getPackageManager();
    Intent i = new Intent("android.intent.action.MAIN");
    i.addCategory("android.intent.category.HOME");
    List<ResolveInfo> lst = pm.queryIntentActivities(i, 0);


    RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);

    if(position < lst.size()) {

        try {
            ApplicationInfo ai = pm.getApplicationInfo(lst.get(position).activityInfo.name, 0);
            int iconId = ai.icon;
            rv.setInt(R.id.widget_item, "setBackgroundResource", iconId);
        } catch (NameNotFoundException e) {
            //Toast.makeText(mContext, "Fail: " + e, Toast.LENGTH_SHORT).show();
            Log.d("Error: ", e.toString());
        }
    }

The issue is with this line:

ApplicationInfo ai = pm.getApplicationInfo(lst.get(position).activityInfo.name, 0);

Does activityInfo.name not return the packagename?

도움이 되었습니까?

해결책

Solved my issue with the following changes.

Instead of getting an int reference to the icon like this:

ApplicationInfo ai = pm.getApplicationInfo(lst.get(position).activityInfo.name, 0);
int iconId = ai.icon;

I used the following code to get the icon as a Drawable:

Drawable icon = lst.get(position).activityInfo.applicationInfo.loadIcon(pm);

I then had to convert the icon from a Drawable to a Bitmap:

Bitmap iconBit = drawableToBitmap(icon);

...

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

Finally, instead of trying to change the background resource of the ImageView like this:

rv.setInt(R.id.widget_item, "setBackgroundResource", iconId);

I used setImageViewBitmap:

rv.setImageViewBitmap(R.id.widget_item, iconBit);

I hope this is helpful to others. I used Kabuko's answer from the following post to convert the Drawable to a Bitmap: How to convert a Drawable to a Bitmap?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top