今天说的这个问题是这样的,在Android App中获取自身或其它某个包名应用的图标时,取到的Drawable并不是实际资源的图标图,而是被启动器或者主题“风格化”后的版本,比如我的一加一的CM13s系统默认主题下启动器中的应用图标会被自动P成这样:
其它如MIUI等也会有类似操作,而无论你是用这样:
1 | getPackageManager().getApplicationIcon(getApplicationInfo()); |
还是这样:
1 2 3 4 5 6 7 8 9 | // Unity应用默认的图标res名叫app_icon,AS会叫ic_launcher,看下manifest中指定的资源ID串就知道了 int iconId = getResources().getIdentifier( "app_icon" , "drawable" , getPackageName()); if (iconId> 0 ) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { dIcon = getResources().getDrawable(iconId, getTheme()); } else { dIcon = getResources().getDrawable(iconId); } } |
取到的都会是修改后的图标图,那么如何取得apk中的原版图标图片呢?答案在此(感谢伟大的google及stackoverflow!):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static Drawable getApplicationIcon(Context context, String packname){ PackageManager pm = context.getPackageManager(); try { PackageInfo pInfo = pm.getPackageInfo(packname, 0 ); int resId = pInfo.applicationInfo.icon; AssetManager assetManager = AssetManager. class .newInstance(); AssetManager. class .getMethod( "addAssetPath" , new Class[]{String. class }).invoke(assetManager, pInfo.applicationInfo.sourceDir); Resources oRes = context.getResources(); Resources resources = new Resources(assetManager, oRes.getDisplayMetrics(), oRes.getConfiguration()); Drawable result = resources.getDrawable(resId); assetManager.close(); return result; } catch (Exception e) { e.printStackTrace(); } return pm.getDefaultActivityIcon(); } |
此段代码在CM13s上测试通过,并能实现预期效果,其它系统版本未测试,如有问题,欢迎留言讨论!
参考文章:
博主友情提示:
如您在评论中需要提及如QQ号、电子邮件地址或其他隐私敏感信息,欢迎使用>>博主专用加密工具v3<<处理后发布,原文只有博主可以看到。
加载更多