LocationServices.SettingsApi เลิกใช้แล้วดังนั้นเราจึงใช้ SettingsClient
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new
LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
จากนั้นตรวจสอบว่าการตั้งค่าตำแหน่งปัจจุบันเป็นที่พอใจหรือไม่ สร้างงาน LocationSettingsResponse:
Task<LocationSettingsResponse> task=LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
จากนั้นเพิ่ม Listener
task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
@Override
public void onComplete(Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(
HomeActivity.this,
101);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible 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 dialog.
break;
}
}
}
});
เพิ่ม onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case 101:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
Toast.makeText(HomeActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(HomeActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
อ้างอิงลิงค์ SettingsClient