How to enable Location access programmatically in android?

114,790

Solution 1

Use below code to check. If it is disabled, dialog box will be generated

public void statusCheck() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();

    }
}

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

Solution 2

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

Solution 3

You can try these methods below:

To check if GPS and network provider is enabled:

public boolean canGetLocation() {
    boolean result = true;
    LocationManager lm;
    boolean gpsEnabled = false;
    boolean networkEnabled = false;

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // exceptions will be thrown if provider is not permitted.
    try {
        gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }

    try {
        networkEnabled = lm
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    return gpsEnabled && networkEnabled;
}

Alert Dialog if the above code returns false:

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

    // Setting Dialog Title
    alertDialog.setTitle("Error!");

    // Setting Dialog Message
    alertDialog.setMessage("Please ");

    // On pressing Settings button
    alertDialog.setPositiveButton(
            getResources().getString(R.string.button_ok),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            });

    alertDialog.show();
}

How to use the two methods above:

if (canGetLocation()) {     
    //DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED                 
} else {
    //SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS                                
    showSettingsAlert();
}

Solution 4

just checkout the following thread: How to check if Location Services are enabled? It provides a pretty good example of how to check whether the location service was enabled or not.

Solution 5

private ActivityResultLauncher<IntentSenderRequest> resolutionForResult;

resolutionForResult = registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(), result -> {
        if(result.getResultCode() == RESULT_OK){
            //Granted
        }else {
            //Not Granted
        }
    });

    private void enableLocationSettings() {
    LocationRequest locationRequest = LocationRequest.create()
            .setInterval(10 * 1000)
            .setFastestInterval(2 * 1000)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

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

    LocationServices
            .getSettingsClient(requireActivity())
            .checkLocationSettings(builder.build())
            .addOnSuccessListener(requireActivity(), (LocationSettingsResponse response) -> {
                // startUpdatingLocation(...);
            })
            .addOnFailureListener(requireActivity(), ex -> {
                if (ex instanceof ResolvableApiException) {
                    try{
                        IntentSenderRequest intentSenderRequest = new IntentSenderRequest.Builder(((ResolvableApiException) ex).getResolution()).build();
                        resolutionForResult.launch(intentSenderRequest);
                    }catch (Exception exception){
                        Log.d(TAG, "enableLocationSettings: "+exception);
                    }
                }
            });
}
Share:
114,790
NarasimhaKolla
Author by

NarasimhaKolla

I work on mobile applications using Java, C#, VB and XML as the graphical front end. Interested in using Web Services for mobile applications

Updated on July 09, 2022

Comments

  • NarasimhaKolla
    NarasimhaKolla almost 2 years

    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 dialog prompt.

    How to enable "Location access" Programmatically in android?