最终效果:
设计
实现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());//显示到文本控件中
显示 :