使用此代码启用GPS并确保已授予位置权限。 最初,当GPS禁用时,onFailureListener将触发并弹出GPS启用对话框,但按ok后将不会触发onSuccessListener,因此您需要从onActivityResult发出当前位置请求,但是如果GPS启用,则在进入应用程序之前,onSuccessListener将触发并且您可以请求从那里获取当前位置。
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
SettingsClient client = LocationServices.getSettingsClient(HomeActivity.this);
Task task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(HomeActivity.this, locationSettingsResponse -> {
// Make your current location request here
});
task.addOnFailureListener(HomeActivity.this, e -> {
if (e instanceof ResolvableApiException) {
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(HomeActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
}
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == REQUEST_CHECK_SETTINGS) {
// Make your current location request here
}
}