我想从GPS提供商和网络提供商那里获取位置信息。我写了下面的代码,并在6以下的android系统中正常工作,并且在android 4.2中进行了检查,并且一切正确,但是当我在android 8中进行检查直到GPS开启时,一切正常,并且可以通过网络或GPS获得位置。但是当GPS关闭时,我无法通过网络提供商获取位置。我的问题是什么,我该如何解决?是否在API 23+上需要启用GPS才能获取位置?我需要在设备设置中启用一个选项吗?
public void createLocation(){
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
gpsLocListener = new MyLocationListener();
networkLocListener = new MyLocationListener();
}
...
public static void checkLocation() {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, networkLocListener);
}
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, networkLocListener);
}
if (!FIND_LOC_ByY_GPS) {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)&& ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocListener); }
} else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocListener); }
//locationManager.requestLocationUpdates(locationManager.PASSIVE_PROVIDER,0,0,passiveLocListener);
}
}
public static class MyLocationListener implements LocationListener {
public MyLocationListener() {
}
@Override
public void onLocationChanged(Location location) {
if (location != null && !callLocationUpdate) {
//Speed
//if (calculateSpeedUser(location) < 13.8889) {
try {
removeLocationUpdate();
callLocationUpdate = true;
if (DEBUG_BASEACTIVITY)
Log.e("GPS Location Changed!", "onLocationChanged/BaseActivity");
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION", "PERMISSION_NOT_GRANTED");
}
//}
get_location_by_LocationUpdate_method = true;
doLocationUpdate(location, true);
getByLocationUpdate = true;
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}