我正在尝试获取在我的应用程序中使用我的位置权限的应用程序列表,并且我正在尝试获取使用位置权限的应用程序:
public void getPermissions(Context context) {
PackageManager packageManager = context.getPackageManager();
final List<PackageInfo> apps = context.getPackageManager()
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for (PackageInfo pi : apps) {
String[] permissions = pi.requestedPermissions;
if (permissions != null) {
for (String permission : permissions) {
Log.d("TAG", permission);
if (permission.equals("android.permission.ACCESS_FINE_LOCATION") || permission.equals("android.permission.ACCESS_COARSE_LOCATION") || permission.equals("android.permission.ACCESS_MOCK_LOCATION") || permission.equals("android.permission.ACCESS_LOCATION_EXTRA_COMMANDS") || permission.equals("android.permission.ACCESS_INSTALL_LOCATION_PROVIDER")) {
String appname=pi.applicationInfo.loadLabel(packageManager).toString();
//ImageView appicon;
//appicon = pi.applicationInfo.setImageDrawable(packageManager);
// Log.e("TAG", "Permission found for "+ appname);
locationArray.add(appname);
}
}
}
}
} //end of getPermissions method
但是有了这个,我会得到多个条目,比如
Angry Birds
Angry Birds
CWM
CWM
CWM
Facebook
有解决方法吗?
答案 0 :(得分:1)
获取重复条目是正常的,因为您跳过所有 PackageInfo
的权限并测试每个条目以查看它是否是与位置相关的权限之一。例如,当您迭代愤怒的小鸟游戏的权限时,您将遇到两个权限(如果我没有弄错ACCESS_FINE和ACCESS_COARSE)并且因为这些权限都满足if条件,您最终会添加愤怒的小鸟两个次。
当你找到第一个许可时,诀窍是突破for (String permission : permissions)
:
for (String permission : permissions) {
Log.d("TAG", permission);
if (permission.equals("android.permission.ACCESS_FINE_LOCATION") || permission.equals("android.permission.ACCESS_COARSE_LOCATION") || permission.equals("android.permission.ACCESS_MOCK_LOCATION") || permission.equals("android.permission.ACCESS_LOCATION_EXTRA_COMMANDS") || permission.equals("android.permission.ACCESS_INSTALL_LOCATION_PROVIDER")) {
String appname=pi.applicationInfo.loadLabel(packageManager).toString();
//ImageView appicon;
//appicon = pi.applicationInfo.setImageDrawable(packageManager);
// Log.e("TAG", "Permission found for "+ appname);
locationArray.add(appname);
break;
}
}
答案 1 :(得分:1)
如果您不想要重复项您可以将locationArray的所有内容添加到HashSet(这将不允许重复)并将HashSet添加回locationArray。
// add elements to hs, including duplicates
HashSet hs = new HashSet();
hs.addAll(localArray);
localArray.clear();
localArray.addAll(hs);
现在localArray不会有任何重复。