最终效果:
设计
实现java代码:
//获取包列表private List<String> getPkgList() {List<String> packages = new ArrayList<String>();try {//使用命令行方式获取包列表Process p = Runtime.getRuntime().exec("pm list packages");//取得命令行输出内容写入流InputStreamReader isr = new InputStreamReader(p.getInputStream(), "utf-8");//读取流BufferedReader br = new BufferedReader(isr);//读取行String line = br.readLine();//遍历包列表while (line != null) {line = line.trim();if (line.length() > 8) {String prefix = line.substring(0, 8);if (prefix.equalsIgnoreCase("package:")) {line = line.substring(8).trim();if (!TextUtils.isEmpty(line)) {//添加到列表packages.add(line);}}}line = br.readLine();//读取下一行}br.close();//关闭流p.destroy();//消毁进程} catch (Throwable t) {System.out.println("读取包列表出错");}return packages;//返回包列表}
//使用系统API获取安装包列表private List<String> getPkgListWithSysApi() {List<String> packages = new ArrayList<String>();try {//取包信息列表List<PackageInfo> packageInfos = this.getApplicationContext().getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);//遍历包列表for (PackageInfo info : packageInfos) {//取包名String pkg = info.packageName;//添加到列表packages.add(pkg);}} catch (Throwable t) {t.printStackTrace();;}return packages;}
调用:
StringBuilder sb = new StringBuilder();//遍历包列表中包名for (String v:getPkgList()) {System.out.println("包名:"+v);sb.append("包名:"+v+"\n");//添加包名到字符串}tv.setText(sb.toString());//显示到文本控件中
//要添加到AndroidManifest.xml不然会获取包列表不完整<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"tools:ignore="QueryAllPackagesPermission" />
显示 :