【问题标题】:How to check if Location Services are enabled?如何检查是否启用了定位服务?
【发布时间】:2014-08-22 07:12:00
【问题描述】:

我正在开发 Android 操作系统上的应用。我不知道如何检查定位服务是否启用。

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

【问题讨论】:

标签: android service location


【解决方案1】:

您可以使用下面的代码来检查是否启用了 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"/>

【讨论】:

  • 感谢您的代码。检查位置管理器:lm.getAllProviders().contains(LocationManager.GPS_PROVIDER)(或NETWORK_PROVIDER)将确保您不会将用户带到没有网络选项的设置页面。
  • 另外:Settings.ACTION_SECURITY_SETTINGS 应该是 Settings.ACTION_LOCATION_SOURCE_SETTINGS
  • 你可以检查一下手机是否处于飞行模式并处理它......stackoverflow.com/questions/4319212/…
  • 我对 lm.isProviderEnabled(LocationManager.GPS_PROVIDER) 有一些问题,它过去总是返回错误。这似乎发生在您使用新版本的 Play Services 时:显示一个对话框,您可以直接从对话框中打开 GPS,而不显示设置活动。当用户从该对话框打开 gps 时,该语句始终返回 false,即使 gps 处于打开状态
  • 也不应该放空的、混乱的、无用的try-catch块
【解决方案2】:

我使用此代码进行检查:

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


} 

【讨论】:

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

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

【讨论】:

  • 太棒了!但更好的是,摆脱强制转换并直接在getSystemService 方法中传递LocationManager.class,因为调用需要API 23 ;-)
  • 或者您可以改用LocationManagerCompat。 :)
  • 使用 return lm != null && lm.isLocationEnabled();而不是 return lm.isLocationEnabled();
  • 谢谢! Settings.Secure.* 需要 API 19。
  • 此代码适用于我的用例,但我无法听取更改。当模式为仅设备且用户禁用定位服务时。 MODE_CHANGED_ACTION 不会触发接收器。但是对于所有其他模式更改,它都会被触发。
【解决方案4】:

迁移到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)
}

【讨论】:

  • 这适用于自 Android 1.0 以来的所有 Android 版本。但请注意Before API version LOLLIPOP [API Level 21], this method would throw SecurityException if the location permissions were not sufficient to use the specified provider. 因此,如果您没有网络或 gps 提供者的权限,它可能会抛出异常,具体取决于启用哪个。查看源代码以获取更多信息。
  • @xuiqzy,谢谢!这是否意味着我们应该首先请求位置许可?
  • 感谢@xuiqzy 关注此问题,该问题现已在更新版本的兼容库中得到修复。
  • 感谢@xuiqzy!我在appcompat:1.2.0 版本上有一个异常,但从1.3.0 错误消失了
【解决方案5】:

您可以使用此代码将用户引导至设置,他们可以在其中启用 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,只需要定位服务。
  • 定位服务始终可用,但不同的提供商可能不可用。
  • @lenik,某些设备提供了一个设置(在“设置 > 个人 > 位置服务 > 访问我的位置”下),即使启用了特定的提供程序,它似乎也可以完全启用/禁用位置检测。我用我正在测试的手机亲眼目睹了这一点,即使 Wifi 和 GPS 都启用了,但它们似乎已经死了……对于我的应用程序。不幸的是,我已经启用了该设置并且无法再重现原始场景,即使禁用“访问我的位置”设置也是如此。所以我不能说该设置是否会影响isProviderEnabled() 和getProviders(true) 方法。
  • ...我只是想把它扔掉,以防其他人遇到同样的问题。我以前从未在我测试过的其他设备上看到过该设置。它似乎是一种系统范围的位置检测终止开关。如果有人对isProviderEnabled() 和getProviders(true) 方法在启用此类设置(或禁用,取决于您如何看待)时如何响应有任何经验,我会非常想知道您遇到了什么。
【解决方案6】:

根据上面的答案,在 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);
}

【讨论】:

  • 无法解析符号 Manifest.permission.ACCESS_COARSE_LOCATION 和 Manifest.permission.ACCESS_FINE_LOCATION
  • 使用android.Manifest.permission.ACCESS_FINE_LOCATION
  • 感谢您注意到这一点,但如果使用更新版本的兼容库,则不再需要权限。
【解决方案7】:

是的,您可以查看以下代码:

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

清单文件中的权限:

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

【讨论】:

    【解决方案8】:

    如果未启用任何提供程序,则“被动”是返回的最佳提供程序。 见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));
        }
    

    【讨论】:

      【解决方案9】:

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

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

      【讨论】:

        【解决方案10】:

        要在安卓谷歌地图中获取当前地理位置位置,你应该打开你的设备位置选项。要检查位置是否打开,你可以简单地调用这个方法来自你的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();
            }
        }
        

        【讨论】:

          【解决方案11】:

          我对 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;
              }
          }
          

          【讨论】:

          • 不需要if-then-else,直接返回locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
          【解决方案12】:

          这是一个非常有用的方法,如果启用了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;
          }
          

          【讨论】:

            【解决方案13】:

            对于科特林

             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"/>
            

            【讨论】:

              【解决方案14】:

              在 Android 8.1 或更低版本上,用户可以通过
              Settings &gt; Location &gt; Mode &gt; 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);
              }
              

              【讨论】:

              • 这个可以简化为manager != null &amp;&amp; LocationManagerCompat.isLocationEnabled(manager);
              • 非常好!可使用旧 API 访问。在 Kotlin 中:manager?.let { LocationManagerCompat.isLocationEnabled(it) } ?: false.
              【解决方案15】:

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

              如果真的打开地图,我会检查 Condition 并且 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();
                  }
              

              【讨论】:

                【解决方案16】:
                private boolean isGpsEnabled()
                {
                    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
                    return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                }
                

                【讨论】:

                  【解决方案17】:

                  您可以请求位置更新并一起显示对话框,就像 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 课程。

                  【讨论】:

                  • 您好,从前两天开始,我一直在努力获取用户的当前位置。我需要用户的当前纬度,我知道可以使用 google api 客户端来完成。但是如何在其中集成棉花糖权限。另外,如果关闭了用户的位置服务,如何启用它。你能帮忙吗?
                  • 嗨!你有很多问题,我无法在 cmets 中回答。请提出一个新问题,以便我更正式地回答!
                  • 我在这里发布了我的问题:stackoverflow.com/questions/39327480/…
                  【解决方案18】:

                  可以用最简单的方式完成

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

                  【讨论】:

                  • 需要 API 19。
                  【解决方案19】:
                  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# 页面将提供更多信息,为什么不使用被动提供程序,而是使用定位模式。

                  【讨论】:

                    【解决方案20】:

                    如果您使用的是 AndroidX,请使用以下代码检查定位服务是否启用:

                    fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))
                    

                    【讨论】:

                    • getSystemService(LocationManager::class.java) 需要 API 23。最好改用 context.getSystemService(Context.LOCATION_SERVICE)。
                    【解决方案21】:

                    要检查网络提供商,您只需将传递给 isProviderEnabled 的字符串更改为 LocationManager.NETWORK_PROVIDER,前提是您同时检查 GPS 提供商和网络提供商的返回值 - 两者均为 false 表示没有位置服务

                    【讨论】:

                      【解决方案22】:
                          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();
                          }
                      

                      【讨论】:

                        猜你喜欢
                        • 2016-04-24
                        • 2011-06-22
                        • 1970-01-01
                        • 2021-03-07
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多