Android菜鸟笔记- 获取未安装的APK图标、版本、包名、名称、是否安装、安装、打开
- - CSDN博客移动开发推荐文章周末闲来无事,把Android的基础知识拿出来复习复习,今天主题是《获取未安装的APK图标、版本、包名、名称、是否安装、跳转安装、打开》. 通常读取APK的图标可以用,PackageManager里面的getApplicationIcon(ApplicationInfo)来得到一个drawable.
周末闲来无事,把Android的基础知识拿出来复习复习,今天主题是《获取未安装的APK图标、版本、包名、名称、是否安装、跳转安装、打开》
通常读取APK的图标可以用,PackageManager里面的getApplicationIcon(ApplicationInfo)来得到一个drawable。但实际使用的时候经常只能得到一个默认的图标,根本不是APK的图标。
参考小米开源文件管理器,结合实践,代码如下:
/* * 采用了新的办法获取APK图标,之前的失败是因为android中存在的一个BUG,通过 * appInfo.publicSourceDir = apkPath;来修正这个问题,详情参见: * http://code.google.com/p/android/issues/detail?id=9151 */ public static Drawable getApkIcon(Context context, String apkPath) { PackageManager pm = context.getPackageManager(); PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES); if (info != null) { ApplicationInfo appInfo = info.applicationInfo; appInfo.sourceDir = apkPath; appInfo.publicSourceDir = apkPath; try { return appInfo.loadIcon(pm); } catch (OutOfMemoryError e) { Log.e("ApkIconLoader", e.toString()); } } return null; }
以下代码段中PackageManager、PackageInfo、ApplicationInfo均同上面一致。
String label = appInfo.loadLabel(mPackManager).toString();
String packageName = appInfo.packageName;
String version = info.versionName==null?"0":info.versionName
private boolean isApkInstalled(String packagename) { PackageManager localPackageManager = getPackageManager(); try { PackageInfo localPackageInfo = localPackageManager.getPackageInfo(packagename, PackageManager.GET_UNINSTALLED_PACKAGES); return true; } catch (PackageManager.NameNotFoundException localNameNotFoundException) { return false; } }
private void installAPK(String apkPath) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.parse("file://" + apkPath), "application/vnd.android.package-archive"); mContext.startActivity(intent); }
</pre><pre name="code" class="java"> private void openAPK(String packagename) { PackageManager packageManager = mContext.getPackageManager(); Intent intent=new Intent(); intent =packageManager.getLaunchIntentForPackage(packagename); mContext.startActivity(intent); }