我正在开发一个应用程序在Android操作系统。我不知道如何检查位置服务是否启用。
我需要一个方法,如果它们被启用,返回“true”,如果没有“false”(所以在最后一种情况下,我可以显示一个对话框来启用它们)。
我正在开发一个应用程序在Android操作系统。我不知道如何检查位置服务是否启用。
我需要一个方法,如果它们被启用,返回“true”,如果没有“false”(所以在最后一种情况下,我可以显示一个对话框来启用它们)。
当前回答
到2020年
最近,最好和最短的方法是
@SuppressWarnings("deprecation")
public static Boolean isLocationEnabled(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// This is a new method provided in API 28
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return lm.isLocationEnabled();
} else {
// This was deprecated in API 28
int mode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_OFF);
return (mode != Settings.Secure.LOCATION_MODE_OFF);
}
}
其他回答
public class LocationUtil {
private static final String TAG = LocationUtil.class.getSimpleName();
public static LocationManager getLocationManager(final Context context) {
return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public static boolean isNetworkProviderEnabled(final Context context) {
return getLocationManager(context).isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public static boolean isGpsProviderEnabled(final Context context) {
return getLocationManager(context).isProviderEnabled(LocationManager.GPS_PROVIDER);
}
// Returns true even if the location services are disabled. Do not use this method to detect location services are enabled.
private static boolean isPassiveProviderEnabled(final Context context) {
return getLocationManager(context).isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
}
public static boolean isLocationModeOn(final Context context) throws Exception {
int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}
public static boolean isLocationEnabled(final Context context) {
try {
return isNetworkProviderEnabled(context) || isGpsProviderEnabled(context) || isLocationModeOn(context);
} catch (Exception e) {
Log.e(TAG, "[isLocationEnabled] error:", e);
}
return false;
}
public static void gotoLocationSettings(final Activity activity, final int requestCode) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activity.startActivityForResult(intent, requestCode);
}
public static String getEnabledProvidersLogMessage(final Context context){
try{
return "[getEnabledProvidersLogMessage] isNetworkProviderEnabled:"+isNetworkProviderEnabled(context) +
", isGpsProviderEnabled:" + isGpsProviderEnabled(context) +
", isLocationModeOn:" + isLocationModeOn(context) +
", isPassiveProviderEnabled(ignored):" + isPassiveProviderEnabled(context);
}catch (Exception e){
Log.e(TAG, "[getEnabledProvidersLogMessage] error:", e);
return "provider error";
}
}
}
使用isLocationEnabled方法检测位置服务是否已启用。
https://github.com/Polidea/RxAndroidBle/issues/327#页面将提供更多信息为什么不使用被动提供程序,而是使用定位模式。
我使用第一个代码开始创建方法isLocationEnabled
private LocationManager locationManager ;
protected boolean isLocationEnabled(){
String le = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(le);
if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
return false;
} else {
return true;
}
}
和我检查条件,如果true打开地图和false给意图ACTION_LOCATION_SOURCE_SETTINGS
if (isLocationEnabled()) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationClient = getFusedLocationProviderClient(this);
locationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
onLocationChanged(location);
Log.e("location", String.valueOf(location.getLongitude()));
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("MapDemoActivity", e.toString());
e.printStackTrace();
}
});
startLocationUpdates();
}
else {
new AlertDialog.Builder(this)
.setTitle("Please activate location")
.setMessage("Click ok to goto settings else exit.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
})
.show();
}
你可以请求位置更新并同时显示对话框,就像GoogleMaps一样。代码如下:
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(getActivity(), 1000);
} catch (IntentSender.SendIntentException ignored) {}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
如果需要更多信息,请检查LocationRequest类。
到2020年
最近,最好和最短的方法是
@SuppressWarnings("deprecation")
public static Boolean isLocationEnabled(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// This is a new method provided in API 28
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return lm.isLocationEnabled();
} else {
// This was deprecated in API 28
int mode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_OFF);
return (mode != Settings.Secure.LOCATION_MODE_OFF);
}
}
如果没有启用任何提供程序,则“passive”是返回的最佳提供程序。 参见https://stackoverflow.com/a/4519414/621690
public boolean isLocationServiceEnabled() {
LocationManager lm = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
String provider = lm.getBestProvider(new Criteria(), true);
return (StringUtils.isNotBlank(provider) &&
!LocationManager.PASSIVE_PROVIDER.equals(provider));
}