我可以使用意图过滤器来收集所有已安装的启动器的列表。麻烦的是拉出对应用程序图标的int引用。下面的代码捕获NameNotFoundException错误。
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());
}
}
问题在于这一行:
ApplicationInfo ai = pm.getApplicationInfo(lst.get(position).activityInfo.name, 0);
activityInfo.name不返回包名吗?
答案 0 :(得分:0)
通过以下更改解决了我的问题。
而不是像这样获得对图标的int引用:
ApplicationInfo ai = pm.getApplicationInfo(lst.get(position).activityInfo.name, 0);
int iconId = ai.icon;
我使用以下代码将图标作为Drawable:
Drawable icon = lst.get(position).activityInfo.applicationInfo.loadIcon(pm);
然后我必须将图标从Drawable转换为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;
}
最后,不要像这样尝试更改ImageView的后台资源:
rv.setInt(R.id.widget_item, "setBackgroundResource", iconId);
我使用了setImageViewBitmap:
rv.setImageViewBitmap(R.id.widget_item, iconBit);
我希望这对其他人有帮助。我用以下帖子中的Kabuko的答案将Drawable转换为位图: How to convert a Drawable to a Bitmap?