Search code examples
androidandroid-gps

How Some Applications like Waze Turn on GPS programmatically?


I searched a lot about turning on GPS programmatically but I didn't find any solution for it. But there are some applications like Waze that aren't system applications and can turn on GPS!

for example in Waze at the show this popup (If your GPS be off!):

enter image description here

And you click on Turn on GPS shows this one:

enter image description here

and GPS will on automatically! How can we do this like Waze?


Solution

  • Following code will show the dialog box you wanted. Add the following dependency.

    compile 'com.google.android.gms:play-services-location:11.0.4'
    

    Make sure that you have connected to googleApiClient befor call this code.

    LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);
    
            builder.setAlwaysShow(true);
            Task<LocationSettingsResponse> result =
                    LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
            result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
                @Override
                public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                    try {
                        task.getResult(ApiException.class);
                    } catch (ApiException exception) {
                        switch (exception.getStatusCode()) {
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                try {
                                    ResolvableApiException resolvable = (ResolvableApiException) exception;
                                    resolvable.startResolutionForResult(YourActivity.this,100);
                                } catch (IntentSender.SendIntentException e) {
                                    Log.d(TAG, e.getMessage());
                                } catch (ClassCastException e) {
                                    Log.d(TAG, e.getMessage());
                                }
                                break;
                        }
                    }
                }
            });