Duplicate entries of installed applications after for loop
-
13-12-2019 - |
Question
I am trying to get a list of applications that uses my location permission in my applications and I'm trying to get the applications that uses the location permission:
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
But with this i will get multiple entries like
Angry Birds
Angry Birds
CWM
CWM
CWM
Facebook
Is there any workaround to solve this?
Solution
It's normal to get duplicate entries because you step over all the permissions of a PackageInfo
and test each one to see if it is one of the location related permission. For example, as you iterate the permission of the Angry Birds game you'll come across two permission(if I'm not mistaken ACCESS_FINE and ACCESS_COARSE) and because those permissions both fulfill the if condition you'll end up adding the Angry Birds two times.
The trick is to break out of the for (String permission : permissions)
when you find the first permission:
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;
}
}
OTHER TIPS
If You do not want duplicates You can add all contents of locationArray to HashSet(which will not allow duplicates) and add HashSet back to locationArray.
// add elements to hs, including duplicates
HashSet hs = new HashSet();
hs.addAll(localArray);
localArray.clear();
localArray.addAll(hs);
Now localArray will not have any duplicates.