Enable GPS within the application

5

Currently to check if 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 starts a dialog where a Intent is used to direct the user to the GPS settings screen. See the intention:

startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

I noticed that in the Google Maps application, you do not have to leave the screen for GPS to be enabled. In the same way a dialogue is launched, however, in this same dialog, when clicking on enable, soon GPS is enabled. I thought maybe it would be a privilege of Google Maps to be from Google itself, but maybe not.

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

    
asked by anonymous 21.04.2017 / 15:47

1 answer

4

As far as I know, the only way is to use the SettingsClient Google, which I think is what the Google Maps app uses.

The API makes it easy for an application to ensure / verify that the 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 that the application needs:

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

Verify that the device settings are configured to meet the requirements of LocationSettingsRequest:

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

The result of the scan can be obtained from the listener assigned to the Task:

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 device settings do not match those required and can be changed by the user (LocationSettingsStatusCodes.RESOLUTION_REQUIRED), a dialog is displayed. The result is received in 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 GPS is powered on. The source or fonts to use (GPS, Wi-Fi, or mobile network) to get the location are chosen based on the LocationSettingsRequest set. A LocationRequest with a PRIORITY_LOW_POWER priority may not turn on GPS if another source is available that guarantees the required accuracy - about 10 km.

References:

21.04.2017 / 16:48