Enable GPS within the app

Asked

Viewed 585 times

5

Currently to check if the GPS is enabled use the following code:

public boolean checkSetting(){
    LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

Returning false is launched a dialog in which a Intent to direct the user to the GPS settings screen. See intent:

startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

I realized that in the Google Maps app does not need to leave the screen for GPS to be enabled. In the same way a dialogue is launched but, in this same dialog, when clicking on enable, soon the GPS is enabled. I thought maybe it would be a privilege of Google Maps to be Google’s own, but maybe not.

How to enable GPS within the application, without entering the settings screen?

  • Do the one with popup asking the user, it seems that it is possible yes: http://stackoverflow.com/a/29744737/5524514 and http://stackoverflow.com/a/29697889/5524514

1 answer

4


That I know the only possibility is to use the Settingsclient from Google, which I believe is what the Google Maps app uses.

The API allows an application to easily ensure/verify that device settings are configured for its needs.

Start by getting a Settingsclient

SettingsClient client = LocationServices.getSettingsClient(this);

Then create a Locationsettingsrequest.Builder and add all the Locationrequests the application needs:

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
     .addLocationRequest(mLocationRequestHighAccuracy)
     .addLocationRequest(mLocationRequestBalancedPowerAccuracy);

Check that your device settings are configured to satisfy those required by Locationsettingsrequest:

Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

The result of the verification can be obtained from Listener assigned to the Task Force:

task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
    @Override
    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
        // Todas as definições do dispositivo estão configuradas para satisfazer as requeridas. 
        // Pode iniciar os pedidos de localização aqui.
        // ...
    }
});

task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        int statusCode = ((ApiException) e).getStatusCode();
        switch (statusCode) {
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                // As definições do dispositivo não satisfazem as requeridas.
                //Mas podem ser alteradas pelo utilizador.
                try {
                    // Mostra um dialog chamando startResolutionForResult(),
                    // o resultado deverá ser verificado em onActivityResult().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MainActivity.this,
                            REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore o erro.
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // As definições do dispositivo não satisfazem as requeridas, não havendo forma de as resolver.
                // Nenhum dialog será mostrado.
                break;
        }
    }
});

If the settings of the device do not satisfy the required ones and these can be changed by the user (Locationsettingsstatuscodes.RESOLUTION_REQUIRED), a dialog is shown. The result is received in the method onActivityResult()

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     final LocationSettingsStates states = LocationSettingsStates.fromIntent(intent);
     switch (requestCode) {
         case REQUEST_CHECK_SETTINGS:
             switch (resultCode) {
                 case Activity.RESULT_OK:
                     // Todas as alterações necessárias foram feitas
                     ...
                     break;
                 case Activity.RESULT_CANCELED:
                     // O usuário cancelou o dialog, não fazendo as alterações requeridas
                     ...
                     break;
                 default:
                     break;
             }
             break;
     }
 }

Note:

This approach does not guarantee that the GPS is switched on.
The source or sources to use (GPS, WI-FI or mobile network) for obtaining the location are chosen according to the Locationsettingsrequest set.
A Locationrequest with a priority of PRIORITY_LOW_POWER may not turn on the GPS if another source is available that guarantees the required accuracy - about 10 km.

References:

  • mLocationRequestBalancedPowerAccuracy is just gps mode?

  • 1

    @diegofm mLocationRequestBalancedPowerAccuracy is an object of the type Locationrequest which serves to define the "quality" of the location service. "Quality" is defined by several values, the most important being the upgrade interval and the priority. PRIORITY_BALANCED_POWER_ACCURACY is a constant to be used in setPriority() defining an accuracy of about 100 metres.

  • 1

    @diegofm The code I used in the answer is from the documentation, in which case the use of attribute names mLocationRequestBalancedPowerAccuracy and mLocationRequestHighAccuracy don’t make much sense since they suggest two different types of precision

  • I found a solution very close to your answer, but explaining a little more about the LocationRequest. I’ll validate the answer, but then if you want to increment the LocationRequest will improve understanding for other people. Abs. Thank you.

  • In what terms? Note that explaining what Locationrequest is is not the focus of the question. It is just a necessary means to get that dialog. Perhaps a new question would be more fruitful.

  • I added a note related to Locationrequest that is relevant to the question.

  • @legal ramaral... really I did not know this issue of battery. Thank you.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.