Android:使用 Fused Location Provider 检查是不是启用了位置服务

Posted

技术标签:

【中文标题】Android:使用 Fused Location Provider 检查是不是启用了位置服务【英文标题】:Android: Check if Location Services Enabled using Fused Location ProviderAndroid:使用 Fused Location Provider 检查是否启用了位置服务 【发布时间】:2015-12-02 02:15:09 【问题描述】:

根据 android 文档:

Google 位置服务 API,Google Play 服务的一部分, 提供了一个更强大的高级框架,可以自动 处理位置提供者、用户移动和位置准确性比 android.location中的平台位置API。

但使用融合位置提供程序(来自 Google Play 服务中的位置 API)我不知道如何检查用户是否启用或禁用了位置。

使用 old android.location 很容易:

locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

但我不想同时使用 Google Play Services 融合位置提供程序和 android 位置。

如何检查用户是否使用 Fused Location Provider 启用了位置?

提前致谢。

【问题讨论】:

嗨,你能把你的实现发布为答案吗? 【参考方案1】:

This android developer training tutorial could help - 基本情况如下:

在 Activity onCreate() 中运行的代码:

 // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) 
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    

    mGoogleApiClient.connect();

    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() 
        @Override
        public void onResult(LocationSettingsResult locationSettingsResult) 

            final Status status = locationSettingsResult.getStatus();
            final LocationSettingsStates LS_state = locationSettingsResult.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(LocationByGPS.this, REQUEST_CHECK_SETTINGS);

                     catch (IntentSender.SendIntentException e) 
                        // Ignore the error.
                    
                    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;
            
        
    );

覆盖此方法:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    switch (requestCode) 
        case REQUEST_CHECK_SETTINGS:
            switch (resultCode) 
                case Activity.RESULT_OK:
                    // All required changes were successfully made
                    GetUserLocation();//FINALLY YOUR OWN METHOD TO GET YOUR USER LOCATION HERE
                    break;
                case Activity.RESULT_CANCELED:
                    // The user was asked to change settings, but chose not to

                    break;
                default:
                    break;
            
            break;
    

记得在你的课堂上实现这些:

public class MyClass extends AppCompatActivity implements
    ActivityCompat.OnRequestPermissionsResultCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener

  protected static final int REQUEST_CHECK_SETTINGS = 0x1;


  /* 
     your code i.e. with the above code etc....
 */

 

Good explanation here in this Google developer link.

干杯!

【讨论】:

我已经通过添加代码和另一个有用的链接来编辑我的答案。 看起来不错 - 我做了一些清理工作并修复了您的链接,但除此之外,这是一个可靠的答案。感谢您的建议,祝您好运! LocationByGPS.this 在哪里? 你甚至修复了官方 Android 开发者教程中的几个错误,太棒了。 @NabeelK 这是外部类,可能是您的 SomethingActivity 类。见官方教程。【参考方案2】:

请参阅SettingsApi:检查您的位置请求,然后确保根据应用的位置需求正确配置设备的系统设置。

【讨论】:

我在这里实现了 SettingsClient :github.com/askfortricks/FusedLocationProviderClient 因为现在不推荐使用 SettingsApi。【参考方案3】:

2020 年现在

最新、最好、最短的方法是

    public boolean isLocationEnabled()
    
     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);

                
    

【讨论】:

如何在不将用户重定向到配置的情况下启用 gps?我的意思是,当用户点击“确定”按钮时,会弹出一个 alertDialog 或snackBar 来启用 GPS。 LocationManagerCompat.isLocationEnabled(context.getSystemService(Context.LOCATION_SERVICE) as LocationManager) 所以你不必检查 SDK 版本。【参考方案4】:

你也可以这样检查:

LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isEnabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

【讨论】:

【参考方案5】:

如果使用 FusedLocationProviderClient, 首先我们需要检查设备中是否启用了位置。

private fun isLocationEnabled(): Boolean 
    val activity: Activity? = this.activity
    val lm = activity?.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
    if (lm != null) 
        val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) 
            lm.isLocationEnabled
         else 
            lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
                    || lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
        
        Log.d(TAG, "isLocationServiceEnabled", enabled)
        return enabled
    
    return false

然后,检查 LocationSettings。

val request = LocationRequest.create()
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)

val settingRequest = LocationSettingsRequest.Builder()
        .addLocationRequest(request)
        .build()
// check Location settings for the request
LocationServices.getSettingsClient(context)
        .checkLocationSettings(settingRequest)
        .addOnSuccessListener 
            // OK!!
            // fusedLocationProviderClient.requestLocationUpdates
        
        .addOnFailureListener   exception ->
            if (exception  is ResolvableApiException) 
                try 
                    exception.startResolutionForResult(activity, RC_LOCATION_SETTINGS)
                 catch (ex: IntentSender.SendIntentException) 
                    // ignore
                
             else 
                // handle other errors
                showFusedDisabledDialog()
            
        

另外,请查看以下链接。

https://developer.android.com/training/location/change-location-settings

【讨论】:

以上是关于Android:使用 Fused Location Provider 检查是不是启用了位置服务的主要内容,如果未能解决你的问题,请参考以下文章

Android:使用 Fused Location Provider 检查是不是启用了位置服务

Android - Google Maps V2 无法使用 Fused Location

如何使用网络在Android中使用Fused Location Provider获取位置?

Android Fused Location 提供商迷路了

Android:关闭位置时,Google Fused Location 不起作用

使用 android fused location api 在 MyLocation 上未显示蓝点