Android Turn on GPS programmatically

Droid By Me
3 min readJan 2, 2019

In our previous article, we have taught you how to get location using FusedLocationProviderClient and we also mentioned in that article that for using this feature, you need to turn on device GPS manually by redirecting to settings of your device.

Programmatically we can turn on GPS in two ways. First, redirect the user to location settings of a device (by code) or another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.

First method:
By using this, the user will be redirected to the Settings page of your device and user has to turn on GPS manually.

Location Settings of device
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);

Second method:
In this method, we will show you code to turn on GPS using android gms location request and setting clients. Here we provide a custom class GpsUtils.java with a code written in it with method turnGPSOn(). The method has a callback listener to check the current status of GPS. If GPS is already turned on, no further code will be determined and callback revert true as GPS is on. Let’s look at the code below and we will show how to use GpsUtils.java.

package com.coders.location;import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.IntentSender;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import static android.content.ContentValues.TAG;public class GpsUtils {private Context context;
private SettingsClient mSettingsClient;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationManager locationManager;
private LocationRequest locationRequest;
public GpsUtils(Context context) {
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
mSettingsClient = LocationServices.getSettingsClient(context);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000);
locationRequest.setFastestInterval(2 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
mLocationSettingsRequest = builder.build();
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
}
// method for turn on GPS
public void turnGPSOn(onGpsListener onGpsListener) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (onGpsListener != null) {
onGpsListener.gpsStatus(true);
}
} else {
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener((Activity) context, new OnSuccessListener<LocationSettingsResponse>() {
@SuppressLint("MissingPermission")
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// GPS is already enable, callback GPS status through listener
if (onGpsListener != null) {
onGpsListener.gpsStatus(true);
}
}
})
.addOnFailureListener((Activity) context, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((Activity) context, AppConstants.GPS_REQUEST);
} catch (IntentSender.SendIntentException sie) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText((Activity) context, errorMessage, Toast.LENGTH_LONG).show();
}
}
});
}
}
public interface onGpsListener {
void gpsStatus(boolean isGPSEnable);
}
}

SettingsClient class is the main key point for interacting with location-based API. This API makes it easy for an app to ensure that the device’s system settings are properly configured for the app’s location needs.

LocationSettingsRequest Specifies the types of location services the client is interested in using. Settings will be checked for optimal functionality of all requested services. Use LocationSettingsRequest.Builder to construct this object.

GPS Dialog will be shown for SettingsClient’s failure callback and it will result in an activity’s onActivityResult(). So basically if the user agrees for turn on GPS, we can enable GPS flag in our activity.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}

and now call GpsUtils class before getting a location.

new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
@Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});

We recommend you to put this code in onCreate() of your activity. So that, turn on GPS and getting a location works well one by one. And also GPS takes some minor delay to trace your device location.

We have provided code in the previous article to get a location. Thus, we made changes for GPS in that code and republish the same code.

Find code here. Code contains previous article example for getting the current location.

--

--