我正在创建一个函数,用于检索设备的已安装应用程序,应用程序包以及每个应用程序具有的权限。问题是我想将所有这些都放入一个JSON文件中,但我不知道该怎么做,这是我编写的程序,但是它不起作用,请,如果有人知道一些帮助,那就是对我来说很重要!预先感谢。
public static void installedApps(Context context) throws IOException{
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packagelist = pm.getInstalledApplications(PackageManager.GET_META_DATA);
CharSequence app;
String pckge;
String[] permissions;
for (ApplicationInfo applicationInfo : packagelist){
app = applicationInfo.loadLabel(context.getPackageManager());
pckge = applicationInfo.packageName;
JSONObject json = new JSONObject();
Log.d("test", "App: "+ applicationInfo.loadLabel(context.getPackageManager()) +", Package: " + applicationInfo.packageName);
try{
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);
//Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if(requestedPermissions != null){
for (int i = 0; i < requestedPermissions.length; i++){
Log.d("test", requestedPermissions[i]);
permissions = requestedPermissions;
JSONArray jsonArray = new JSONArray();
try{
json.put("app", app);
json.put("package", pckge);
jsonArray.put(Integer.parseInt("permission"), permissions);
}catch (JSONException e) {
e.printStackTrace();
}
}
}
//primero cargar en un array todos los datos, y pasarlos a un json llamandolos
}catch (PackageManager.NameNotFoundException e){
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
我可能会选择这样的东西:
public static void installedApps(Context context) {
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packagelist = pm.getInstalledApplications(PackageManager.GET_META_DATA);
JSONObject resp = new JSONObject();
for (ApplicationInfo applicationInfo : packagelist) {
CharSequence app = applicationInfo.loadLabel(context.getPackageManager());
String pckge = applicationInfo.packageName;
JSONObject json = new JSONObject();
try {
//Get Permissions
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
json.put("app", app);
json.put("package", pckge);
JSONArray jsonArray = new JSONArray();
for (String requestedPermission : requestedPermissions) {
jsonArray.put(requestedPermission);
}
json.put("permission", jsonArray);
resp.put(applicationInfo.name, json); // something to identify each app
}
} catch (Exception e) {
e.printStackTrace();
}
}
// return resp.toString() or store in file or whatever you want to do
}
答案 1 :(得分:0)
我很确定这行有问题,
permissions = requestedPermissions;
...
jsonArray.put(Integer.parseInt("permission"), permissions);
由于您在顶部定义了permissions
数组,因此您将看到最终的requestPermission
项经过jsonArray
次添加到packageList.size()
中。
将permission
带入循环。它会解决您的问题。