【发布时间】:2018-04-19 15:48:00
【问题描述】:
我的应用依赖于 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.
}
}
}
});
}
【问题讨论】:
-
您可以随时再次调用权限请求。没有什么能阻止这一点。弹出一个对话框来解释没有权限应用程序无法运行可能会很好。
-
是的,但 GPS 确实必不可少,并且在应用程序运行时一直使用它。那么如果用户不允许打开 GPS,有没有办法再次显示对话框或关闭应用程序?
-
如果你想减少样板,我可以建议你看看这个库:github.com/tbruyelle/RxPermissions。我在生产中使用它,它就像一个魅力。
-
如何在onActivityResult失败时再次调用startResolutionForResult,通过启动一个新线程,防止函数调用的堆栈溢出?
-
为什么不直接使用
ContextCompat.checkSelfPermission来检查权限并阻止用户做任何事情,这是不被授予的
标签: android gps location android-6.0-marshmallow