2

I am trying to enable GPS settings using dialog box with the user confirmation.

here is the code

    public void turnGPSOn() {
            LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
            boolean enabled = service
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (!enabled) {
                      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        this);
                      alertDialogBuilder
                        .setMessage("GPS is disabled in your device. Enable it?")
                        .setCancelable(false)
                        .setPositiveButton("Enable GPS",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
/** Here it's leading to GPS setting options*/
                                        Intent callGPSSettingIntent = new Intent(
                                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                        startActivity(callGPSSettingIntent);
                                    }
                                });
                alertDialogBuilder.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alert = alertDialogBuilder.create();
                alert.show();
            }
        }

Above code will lead the user to gps setting options.But i have seen in many apps(recent apps) where after confirmation gps setting will be enabled to High-Accuracy automatically.

My Question is i need to enable GPS setting to Battery Saving mode(or any other) after user confirmation(Dialog 'yes') without going to GPS settings.

MinSDK:9
TargetSDK:23
BuildToolVer:23.0.1

Regards.

Madhukar Hebbar
  • 3,113
  • 5
  • 41
  • 69
  • 1
    for ref, may help - http://stackoverflow.com/questions/28759454/enabling-location-with-mode-high-accuracy-or-battery-saving-without-user-needing – Pararth Oct 23 '15 at 06:31

1 Answers1

4

You can use GoogleApiClient for that.

  private static GoogleApiClient client;
  private  Location mLastLocation;

Also implement necessary interfaces.

GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener

I have implemented these above interfaces

initialize GoogleApiClient in OnCreate like this. Add necessary Apis.

  if (client == null) {
        client = new GoogleApiClient.Builder(mContext)
                .enableAutoManage(context, 0, this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

You can set accuracy by setting priority in the location Request.

These are different priorities.

LocationRequest.PRIORITY_HIGH_ACCURACY
LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
LocationRequest.PRIORITY_LOW_POWER
LocationRequest.PRIORITY_NO_POWER

In the onConnected method make the location request.

The onConnected method is available in GoogleApiClient.ConnectionCallbacks interface.

@Override
public void onConnected(Bundle bundle) {

    final 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);
    result = LocationServices.SettingsApi.checkLocationSettings(client, builder.build());

    if (result != null) {
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();

                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a optionsDialog.
                        try {
                            // Show the optionsDialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            if (status.hasResolution()) {
                                status.startResolutionForResult(getActivity(), 1000);
                            }
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the optionsDialog.
                        break;
                }
            }
        });
    }
}

startResolutionForResult() This function shows the dialog for enabling GPS without going to the Location Settings

1000 is the REQUEST_CODE

And retrieve the location in onActivity Result

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if ((resultCode == Activity.RESULT_OK) && (requestCode == 1000)) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(client);
        Log.e("location", mLastLocation.getLatitude() + ":" + mLastLocation.getLongitude());
    }
}
Emil
  • 2,786
  • 20
  • 24
  • Thanks for the help. Let me check with this code but I am not using google map and i think above code will make location setting to High-Accuracy. My application is a background app which needs minimal info about location. Is there any way to set location setting to Battery saving mode automatically? – Madhukar Hebbar Oct 23 '15 at 06:04
  • You can set the priority of the Location Request to set battery saving mode. Check the edited answer – Emil Oct 23 '15 at 06:23
  • @Boss so glad I found this. How can I keep popping the dialog if the user pressed no ? – Bogdan Daniel Nov 15 '15 at 22:32
  • @BogdanDaniel you can check that in the `onActivityResult`. Check for the resultcode `RESULT_CANCELED` – Emil Nov 16 '15 at 09:54
  • @Boss and what should I put inside that ? `status.startResolutionForResult(getActivity(), 1000);` or the entire onConnected ? – Bogdan Daniel Apr 22 '16 at 16:28
  • @BogdanDaniel The `onConnected` method is called by the system. So we just call the `startResolutionForResult()` method. – Emil Apr 23 '16 at 06:44
  • @Emil in fragment I am not getting onActivityResult called, I get it in activity instead.. I can take the value from activity to fragment I know but is it a way to make it work in fragment it self.. ? – Aalap Patel Aug 17 '17 at 16:15
  • @AalapPatel I don't think its possible. You have to bypass your ``onActivityResult`` to your fragment. ``public void startResolutionForResult (Activity activity, int requestCode)`` takes Activity as a parameter. And its documentation says as below: An Activity context to use to resolve the issue. The activity's onActivityResult method will be invoked after the user is done. If the resultCode is RESULT_OK, the application should try to connect again. – Emil Aug 18 '17 at 06:32
  • @Emil Thank you, this makes sense. – Aalap Patel Aug 18 '17 at 13:19