Friday 5 February 2016

Enable Location Services and GPS programmatically (without navigating to the location settings)

In this post, we have learn about enabling  Location Services and GPS programmatically (without navigating to the location settings).

First,
1) Add add google play services into android studio.

2) Create new project in android studio.

3)Implement GoogleApiClinet for enabling  Location Services.

Once play services are available on the device, build the GoogleApiClient by calling buildGoogleApiClient() method.

 Connect to google api client by calling googleApiClient.connect() method. By calling this, onConnectionFailed(), onConnected() and onConnectionSuspended() will be triggered depending upon the connection status.

Add the below code to your main activity and run the project.

      private void enableLoc() {
        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {

                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            googleApiClient.connect();
                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult) {

                            Log.d("Location error","Location error " + connectionResult.getErrorCode());
                        }
                    }).build();
            googleApiClient.connect();

            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);

            PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(MainActivity.this, REQUEST_LOCATION);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                    }
                }
            });
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUEST_LOCATION:
                switch (resultCode) {
                    case Activity.RESULT_CANCELED: {
                        // The user was asked to change settings, but chose not to
                        finish();
                        break;
                    }
                    default: {
                        break;
                    }
                }
                break;
        }

    }

Output:

6 comments:

  1. Hi
    Let me know that how this code run on android eclipse. please suggest me regard this.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Your solution helped me. I am looking for disabling in same way? Can you please help?

    ReplyDelete
  4. great post!

    Thanks,
    Jessica (http://becomeceleb.com?myProfile)

    ReplyDelete
  5. hola amigo me gustaria saber como puedo verificar si el gps esta activo y si no lo esta que se ejecute el codigo del cuadro de dialogo, automaticamente para habilitarlo. muchas gracias por tu ejemplo

    ReplyDelete
  6. Excellent post, It's a really friendly article. Good Blogger,
    //naveedpc.org/

    ReplyDelete