How to enable Location access programmatically in android?

后端 未结 6 863
暖寄归人
暖寄归人 2020-12-02 11:37

I am working on map related android application and I need to check location access enable or not in client side development if location services is not enable show the dial

6条回答
  •  旧时难觅i
    2020-12-02 11:45

    Here is a simple way of programmatically enabling location like Maps app:

    protected void enableLocationSettings() {
           LocationRequest locationRequest = LocationRequest.create()
                 .setInterval(LOCATION_UPDATE_INTERVAL)
                 .setFastestInterval(LOCATION_UPDATE_FASTEST_INTERVAL)
                 .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);
    
            LocationServices
                    .getSettingsClient(this)
                    .checkLocationSettings(builder.build())
                    .addOnSuccessListener(this, (LocationSettingsResponse response) -> {
                        // startUpdatingLocation(...);
                    })
                    .addOnFailureListener(this, ex -> {
                        if (ex instanceof ResolvableApiException) {
                            // Location settings are NOT satisfied,  but this can be fixed  by showing the user a dialog.
                            try {
                                // Show the dialog by calling startResolutionForResult(),  and check the result in onActivityResult().
                                ResolvableApiException resolvable = (ResolvableApiException) ex;
                                resolvable.startResolutionForResult(TrackingListActivity.this, REQUEST_CODE_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sendEx) {
                                // Ignore the error.
                            }
                        }
                    });
     }
    

    And onActivityResult:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (REQUEST_CODE_CHECK_SETTINGS == requestCode) {
            if(Activity.RESULT_OK == resultCode){
                //user clicked OK, you can startUpdatingLocation(...);
    
            }else{
                //user clicked cancel: informUserImportanceOfLocationAndPresentRequestAgain();
            }
        }
    }
    

    You can see the documentation here: https://developer.android.com/training/location/change-location-settings

提交回复
热议问题