在我的应用程序中,我可以选择让用户打开设置并允许位置。导航到设置屏幕后,如何知道用户打开了该位置?这是启动设置活动的方式。
if(!gps_enabled && !network_enabled) {
// notify user
new AlertDialog.Builder(this)
.setMessage(R.string.gps_network_not_enabled)
.setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), isGpsTurnedOnResult );
}
}).setNegativeButton(R.string.Cancel,null)
.show();
}
这是我尝试获得结果的方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
当我检查data
时发现它为空,是否有办法知道用户打开了该位置?当然,我可以使用LocationManager
进行检查,但这不是我想要的解决方案,除非这是唯一可行的方法。
答案 0 :(得分:0)
构建位置设置
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
// ...
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
提示用户更改位置设置
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
}
});
task.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception 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(MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
}
}
}
});