Android 6.0 以下:使用
Settings.Secure.ALLOW_MOCK_LOCATION
判断。
// Android 6.0 以下:是否开启【允许模拟位置】
boolean canMockPosition = Settings.Secure.getInt(getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0
Android 6.0 及以上:没有【允许模拟位置】选项,同时弃用了
Settings.Secure.ALLOW_MOCK_LOCATION
,无法通过上面的方法判断。增加了【选择模拟位置信息应用】的方法,需要选择使用模拟位置的应用。但是不知道怎么获取当前选择的应用,因此通过是否能够成功执行addTestProvider方法来进行判断,如果没有选择当前的应用,则addTestProvider会抛出异常。网上的方法不对,自己在这里做了更正
/**
* 判断是否打开了允许虚拟位置,android6.0以下及以上都可用
*
* @return boolean
*/
public static boolean isAllowMockLocation() {
boolean canMockPosition = false;
if (Build.VERSION.SDK_INT <= 22) {//6.0以下
canMockPosition = (Settings.Secure.getInt(Context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0);
} else {
try {
LocationManager locationManager = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE);//获得LocationManager引用
String providerStr = LocationManager.GPS_PROVIDER;
LocationProvider provider = locationManager.getProvider(providerStr);
if (provider != null) {
locationManager.addTestProvider(
provider.getName()
, provider.requiresNetwork()
, provider.requiresSatellite()
, provider.requiresCell()
, provider.hasMonetaryCost()
, provider.supportsAltitude()
, provider.supportsSpeed()
, provider.supportsBearing()
, provider.getPowerRequirement()
, provider.getAccuracy());
} else {
locationManager.addTestProvider(
providerStr
, true, true, false, false, true, true, true
, Criteria.POWER_HIGH, Criteria.ACCURACY_FINE);
}
locationManager.setTestProviderEnabled(providerStr, true);
locationManager.setTestProviderStatus(providerStr, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
// 模拟位置可用
canMockPosition = true;
} catch (SecurityException e) {
canMockPosition = false;
}
}
return canMockPosition;
}