Sunday, September 1, 2013

Detect fake/mock GPS apps on Android device

While we are working with location APIs in any Android App, we have to make sure that user is not using any fake/mock GPS apps. We can detect fake/mock GPS apps using two ways:
  1. Detect mock location is enabled in developer settings.
  2. Detect apps installed on device who are using mock location permissions.
To detect the mock location settings:-
public static boolean isMockLocationSettingsON(Context context) {
        // returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(context.getContentResolver(),
        Settings.Secure.ALLOW_MOCK_LOCATION).equals("0")) {
       return false;
} else {
return true;
}
}

To detect the mock location permissions:-
public static ArrayList getListOfMockPermissionApps(Context context) {
ArrayList mockPermissionApps = new ArrayList();
PackageManager pm = context.getPackageManager();
List packages = pm
.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo applicationInfo : packages) {
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++) {
if (requestedPermissions[i]
.equals("android.permission.ACCESS_MOCK_LOCATION")
&& !applicationInfo.packageName.equals(context
.getPackageName())) {
mockPermissionApps.add(applicationInfo.packageName);
}
}
}
} catch (NameNotFoundException e) {
}
}
return mockPermissionApps;
}