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

Mer*_*yth 208 service android location

我正在Android OS上开发一款应用.我不知道如何检查是否启用了位置服务.

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

Sha*_*wal 342

您可以使用以下代码检查是否启用了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();    
}
Run Code Online (Sandbox Code Playgroud)

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

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Run Code Online (Sandbox Code Playgroud)

  • 另外:`Settings.ACTION_SECURITY_SETTINGS`应为`Settings.ACTION_LOCATION_SOURCE_SETTINGS` (26认同)
  • 也不应该放空,混乱,无用的try-catch块 (6认同)
  • 你可以检查手机是否处于飞行模式并处理它...... http://stackoverflow.com/questions/4319212/how-can-one-detect-airplane-mode-on-android (2认同)
  • 我遇到了lm.isProviderEnabled(LocationManager.GPS_PROVIDER)的一些问题,它常常返回false.当您使用新版本的Play服务时,似乎会出现这种情况:显示一个对话框,您可以从对话框中打开gps,而不显示设置活动.当用户从该对话框中转换gps时,即使启用了gps,该语句也始终返回false (2认同)

小智 221

我使用此代码进行检查:

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


} 
Run Code Online (Sandbox Code Playgroud)

  • 为清楚起见,可能希望在catch块中返回false.否则将locationMode初始化为Settings.Secure.LOCATION_MODE_OFF. (7认同)
  • 这个答案应该被接受为正确的答案.locationManager.isProviderEnabled()方法在我的4.4设备上不可靠(并且我看到其他开发人员在其他操作系统版本上也有同样的问题).在我的情况下,在每种情况下它都会返回GPS(如果启用了位置服务,则无关紧要).感谢这个伟大的解决方案! (3认同)
  • 这是一个很好的答案,因为它适用于新旧Android位置API. (2认同)
  • LOCATION_PROVIDERS_ALLOWED - [link](http://developer.android.com/reference/android/provider/Settings.Secure.html#LOCATION_PROVIDERS_ALLOWED)此常量在API级别19中已弃用.我们必须使用LOCATION_MODE和MODE_CHANGED_ACTION(或PROVIDERS_CHANGED_ACTION) (2认同)
  • 这在我的测试设备,三星SHV-E160K,android 4.1.2,API 16上不起作用.虽然我让GPS离线,但这个功能仍然是真的.我测试了Android Nougat,它的API 7.1 (2认同)

len*_*nik 33

您可以使用此代码将用户定向到设置,在那里他们可以启用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();
    }
Run Code Online (Sandbox Code Playgroud)

  • @lenik,某些设备提供了一个设置(在"设置>个人>位置服务>访问我的位置"下),它似乎完全启用/禁用位置检测,即使启用了特定的提供程序.我亲眼看到了这款带有我正在测试的手机,即使启用了Wifi和GPS,它们也显得已经死了......我的应用程序.不幸的是,我启用了设置,并且无法再重现原始方案,即使禁用"访问我的位置"设置也是如此.所以我不能说这个设置是否会影响`isProviderEnabled()`和`getProviders(true)`方法. (3认同)
  • 非常感谢,但我不需要代码来检查 GPS,而只需要位置服务。 (2认同)

May*_*rma 31

截至2019年

最新,最好和最短的方法是

public static Boolean isLocationEnabled(Context context)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// This is new method provided in API 28
            LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            return lm.isLocationEnabled();
        } else {
// This is 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);

        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 优秀 !但更好的是,摆脱强制转换并直接在 `getSystemService` 方法中传递 `LocationManager.class`,因为调用需要 API 23 ;-) (2认同)
  • 或者,您可以改用[LocationManagerCompat](https://developer.android.com/reference/androidx/core/location/LocationManagerCompat)。:) (2认同)
  • 使用 return lm != null &amp;&amp; lm.isLocationEnabled(); 而不是 return lm.isLocationEnabled(); (2认同)

ZaB*_*anc 15

解决上面的答案,在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);
}
Run Code Online (Sandbox Code Playgroud)


Sun*_*nny 10

迁移到Android X并使用

implementation 'androidx.appcompat:appcompat:1.1.0'
Run Code Online (Sandbox Code Playgroud)

并使用LocationManagerCompat

在java中

private boolean isLocationEnabled(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return LocationManagerCompat.isLocationEnabled(locationManager);
}
Run Code Online (Sandbox Code Playgroud)

在科特林

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


Ris*_*nha 7

如果未启用提供程序,则"被动"是返回的最佳提供程序.请参阅/sf/answers/316359011/

    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));
    }
Run Code Online (Sandbox Code Playgroud)


Aru*_*mar 7

是的你可以查看以下代码:

public boolean isGPSEnabled(Context mContext) 
{
    LocationManager lm = (LocationManager)
    mContext.getSystemService(Context.LOCATION_SERVICE);
    return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
Run Code Online (Sandbox Code Playgroud)

拥有清单文件中的权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)


Jua*_*ler 7

在 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);
}
Run Code Online (Sandbox Code Playgroud)


tse*_*ann 6

这个if子句容易检查我认为位置服务是否可用:

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

}
Run Code Online (Sandbox Code Playgroud)