You can use the below code. With the below code it will ask to turn the GPS on .
public class Activity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 600000; // 10 min
private static int FATEST_INTERVAL = 600000; // 10 min
private static int DISPLACEMENT = 5; // 5 meters
PendingResult<LocationSettingsResult> result;
AlertDialog.Builder alertDialogBuilder;
LinearLayout parent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
alertDialogBuilder = new AlertDialog.Builder(Activity.this);
parent = new LinearLayout(ActivitySetting.this);
parent.setGravity(Gravity.CENTER);
parent.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
alertDialogBuilder.setTitle("name");
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));
result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
// final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
alertDialogBuilder.setMessage("Turn On GPS");
alertDialogBuilder.setView(parent);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(ActivitySetting.this, 1000);
} catch (IntentSender.SendIntentException e) {
// check error.
}
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
// Show the dialog by calling startResolutionForResult(),
finish();
} catch (Exception e) {
// check error.
}
}
});
alertDialogBuilder.create();
alertDialogBuilder.show();
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// you can do here what ever you want.
break;
}
}
});
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case 1000:
switch (resultCode) {
case Activity.RESULT_OK:
// If user has active gps you will get it here
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to turn on
break;
default:
break;
}
break;
}
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
/**
* Google api callback methods
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("fsAil", "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
}
}
Here API <= 21
gps permission will be granted automatically(if you have defined permission on manifest) and for marshmallow and above you need to ask for runtime permission(also add permission in manifest) but to turn on GPS after permission granted
you can use the above code.
With this code one alertbox comes up and ask to turn on the GPS(if not active). So you can directly turn on GPS with the above code.
Hope this help you.
Cheers!!