如何检查位置服务是否已启用?

我正在开发一个应用程序在Android操作系统。我不知道如何检查位置服务是否启用。

我需要一个方法,如果它们被启用,返回“true”,如果没有“false”(所以在最后一种情况下,我可以显示一个对话框来启用它们)。

289999 次浏览

您可以使用此代码引导用户到设置,在那里他们可以启用GPS:

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
new AlertDialog.Builder(context)
.setTitle(R.string.gps_not_found_title)  // GPS not found
.setMessage(R.string.gps_not_found_message) // Want to enable?
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
owner.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.no, null)
.show();
}

您可以使用下面的代码来检查是否启用gps提供程序和网络提供程序。

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;


try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}


try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}


if(!gps_enabled && !network_enabled) {
// notify user
new AlertDialog.Builder(context)
.setMessage(R.string.gps_network_not_enabled)
.setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.Cancel,null)
.show();
}

在清单文件中,您需要添加以下权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

要检查网络提供者,你只需要将传递给isProviderEnabled的字符串更改为LocationManager。NETWORK_PROVIDER如果你检查GPS提供者和网络提供者的返回值-两个false都表示没有位置服务

在我看来,这个if子句很容易检查位置服务是否可用:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//All location services are disabled


}

如果没有启用任何提供程序,则“passive”是返回的最佳提供程序。 看到https://stackoverflow.com/a/4519414/621690 < / p >

    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));
}

我使用下面的代码来检查:

public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);


} catch (SettingNotFoundException e) {
e.printStackTrace();
return false;
}


return locationMode != Settings.Secure.LOCATION_MODE_OFF;


}else{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}




}
private boolean isGpsEnabled()
{
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

要在android谷歌地图中获取当前的地理位置,您可以使用应该打开你的设备位置吗选项。要检查位置是否打开,可以从onCreate()方法简单地调用此方法。

private void checkGPSStatus() {
LocationManager locationManager = null;
boolean gps_enabled = false;
boolean network_enabled = false;
if ( locationManager == null ) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex){}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex){}
if ( !gps_enabled && !network_enabled ){
AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this);
dialog.setMessage("GPS not enabled");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
//this will navigate user to the device location settings screen
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
AlertDialog alert = dialog.create();
alert.show();
}
}

是的,你可以检查以下是代码:

public boolean isGPSEnabled(Context mContext)
{
LocationManager lm = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

在manifest文件中的权限下:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

我对NETWORK_PROVIDER使用这样的方式,但你可以为全球定位系统(GPS)添加和。

LocationManager locationManager;

onCreate我放

   isLocationEnabled();
if(!isLocationEnabled()) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.network_not_enabled)
.setMessage(R.string.open_location_settings)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}

检查方法

protected boolean isLocationEnabled(){
String le = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(le);
if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
return false;
} else {
return true;
}
}

这是一个非常有用的方法,如果启用了Location services,则返回"true":

public static boolean locationServicesEnabled(Context context) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean net_enabled = false;


try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e(TAG,"Exception gps_enabled");
}


try {
net_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e(TAG,"Exception network_enabled");
}
return gps_enabled || net_enabled;
}

你可以请求位置更新并同时显示对话框,就像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类。

根据上面的答案,在API 23中,你需要添加“危险”权限检查以及检查系统本身:

public static boolean isLocationServicesAvailable(Context context) {
int locationMode = 0;
String locationProviders;
boolean isAvailable = false;


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}


isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF);
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
isAvailable = !TextUtils.isEmpty(locationProviders);
}


boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);


return isAvailable && (coarsePermissionCheck || finePermissionCheck);
}

我使用第一个代码开始创建方法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();
}

enter image description here

在芬兰湾的科特林

 private fun isLocationEnabled(mContext: Context): Boolean {
val lm = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || lm.isProviderEnabled(
LocationManager.NETWORK_PROVIDER)
}

对话框

private fun showLocationIsDisabledAlert() {
alert("We can't show your position because you generally disabled the location service for your device.") {
yesButton {
}
neutralPressed("Settings") {
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
}.show()
}

像这样调用

 if (!isLocationEnabled(this.context)) {
showLocationIsDisabledAlert()
}

提示:对话框需要以下导入(android studio应该为你处理这个)

import org.jetbrains.anko.alert
import org.jetbrains.anko.noButton

在清单中,您需要以下权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

能用最简单的方法做吗

private boolean isLocationEnabled(Context context){
int mode =Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_OFF);
final boolean enabled = (mode != android.provider.Settings.Secure.LOCATION_MODE_OFF);
return enabled;
}

到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);
}
}

迁移到AndroidX并使用

implementation 'androidx.appcompat:appcompat:1.3.0'

并使用LocationManagerCompat

在Java中

private boolean isLocationEnabled(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return LocationManagerCompat.isLocationEnabled(locationManager);
}

在芬兰湾的科特林

private fun isLocationEnabled(context: Context): Boolean {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return LocationManagerCompat.isLocationEnabled(locationManager)
}

如果你正在使用AndroidX,使用下面的代码来检查位置服务是否启用:

fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))
    LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;


try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception e){
e.printStackTrace();
}


try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception e){
e.printStackTrace();
}


if(!gps_enabled && !network_enabled) {
// notify user
new AlertDialog.Builder(this)
.setMessage("Please turn on Location to continue")
.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}


}).
setNegativeButton("Cancel",null)
.show();
}
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#页面将给出更多的信息,为什么不使用被动提供程序,而是使用定位模式。

在Android 8.1或以下用户可以启用“电池节省”;模式从
Settings > Location > Mode > Battery Saving
此模式只使用WiFi, Bluetooth or mobile data而不是GPS来确定用户位置

这就是为什么你必须检查网络提供者是否启用,locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)是否不够。

如果你正在使用androidx,这段代码将检查你正在运行的SDK版本,并调用相应的提供商:

public boolean isLocationEnabled(Context context) {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return manager != null && LocationManagerCompat.isLocationEnabled(manager);
}
You can also use extension function.
------------------------------------


fun Context.isLocationEnabled(): Boolean{
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return LocationManagerCompat.isLocationEnabled(locationManager)}