我的应用依赖于GPS信号,因此我要求应用启动时的用户启用GPS。但是,如果用户拒绝,应用程序将继续运行。
GPS对我的应用程序至关重要,因此如果用户拒绝,我想再次显示该对话框。如果不可能,只需在用户未授予许可的情况下关闭应用程序。
你能帮忙吗?
非常感谢。
protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
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,
1);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
}
}
}
});
}
答案 0 :(得分:1)
创建一个监听器,用于监听设备GPS上的模式更改,在您的应用程序库中实现监听器。然后相应地处理这些功能。如果GPS已启用,则应用程序将继续运行,否则会显示一个警告框,要求用户启用gps,因为所有ur活动都是从您的应用程序库扩展。
您可以查看答案here,了解如何确定GPS是否已启用。
您还可以查看本教程here,了解如何创建监听器。
答案 1 :(得分:0)
解决方案是覆盖onActivityResult方法并使用匹配的requestCode处理它。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 6) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}else{
createLocationRequest();
}
}
}