java获取apk的所有类,在Android中获取所有已安装的应用程序图标:java.lang.ClassCastException...

There is a java.lang.ClassCastException when I am trying to get a installed applications icon.

Here is my code.

public Bitmap getAppIcon(String path) {

PackageInfo pi = pm.getPackageArchiveInfo(path, 0);

pi.applicationInfo.sourceDir = path;

pi.applicationInfo.publicSourceDir = path;

Drawable icon = pi.applicationInfo.loadIcon(pm);

Bitmap APKicon = ((BitmapDrawable) icon).getBitmap();

return APKicon;

}

where, pm is

PackageManager pm = getPackageManager();

and the error shown in the LogCat is

Caused by: java.lang.ClassCastException: android.graphics.drawable.NinePatchDrawable cannot be cast to android.graphics.drawable.BitmapDrawable

Hope anybody can help me.

解决方案

Your Problem is that your Icon is no instance of BitmapDrawable, one can check like that:

Bitmap APKicon;

if(icon instanceof BitmapDrawable) {

APKicon = ((BitmapDrawable)icon).getBitmap();

}

in this case your solution would be right, one can just cast it, but if not (and that is your case) one needs to do something like that:

else{

Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(),icon.getIntrinsicHeight(), Config.ARGB_8888);

Canvas canvas = new Canvas(bitmap);

icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());

icon.draw(canvas);

APKicon = bitmap;

}

this solution will work in any case

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值