19

根据Android文档:

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

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

使用 android.location的很容易:

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

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

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

提前致谢。

4

5 回答 5

38

这个 android 开发人员培训教程可能会有所帮助- 以下是基础知识:

在 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....
 */

 }

在这个谷歌开发者链接中很好的解释。

干杯!

于 2016-03-02T16:36:35.587 回答
17

请参阅SettingsApi:检查您的位置请求,然后确保设备的系统设置已针对应用程序的位置需求进行了正确配置。

于 2015-09-06T12:01:14.900 回答
8

就像现在在 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);

                }
    }
于 2019-01-04T06:19:55.537 回答
2

您也可以像这样检查:

LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isEnabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
于 2018-08-10T10:36:44.777 回答
0

如果使用 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

于 2020-01-18T15:50:19.097 回答