这种新的和令人敬畏的安全功能是RUN-TIME Permission
我正在努力理解它并为此制作一个演示但是我想到的一个问题是当我处理DIALOG的用户许可时.
如何处理" 永不再问 "
假设我的应用程序必须需要位置/联系人,但用户拒绝它"不要再问".
我能做些什么?并非所有用户都了解我的字段是必需的.
有什么建议吗?
首先,你需要实现OnRequestPermissionsResultCallback
Listener
的ActivityCompat
在你的类Activity
并重写 void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
的方法来检查用户是否允许或拒绝许可
你可以这样做.在这里,我检查权限访问WRITE_EXTERNAL_STORAGE
:
int REQUEST_STORAGE = 1; private void checkPermissions() { if (hasStoragePermissionGranted()) { // you can do whatever you want } else { requestPermission(); } } public boolean hasPermissionGranted(){ return ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; } public void requestPermission() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ ActivityCompat.requestPermissions(MainActivity.this, {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE); } }
onRequestPermissionsResult()
当用户允许或拒绝来自运行时权限对话框的权限时,将调用此方法.
您还可以处理用户已选中从未显示运行时权限对话框的情况,您可以显示Snackbar或按钮以将用户重定向到您的应用程序设置页面,因为您在用户检查后无法显示权限对话框"Never ask again"
.
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_STORAGE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Storage permission is enabled canSendAttachments = true; systemLogsCheckbox.setEnabled(true); } else if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivtity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { //User has deny from permission dialog Snackbar.make(mainLayout, getResources().getString("Please enable storage permission"), Snackbar.LENGTH_INDEFINITE) .setAction("OK", new View.OnClickListener() { @Override public void onClick(View view) { ActivityCompat.requestPermissions(MainActivity.this, {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE); } }) .show(); } else { // User has deny permission and checked never show permission dialog so you can redirect to Application settings page Snackbar.make(mainLayout, getResources().getString("Please enable permission from settings"), Snackbar.LENGTH_INDEFINITE) .setAction("OK", new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", MainActivity.this.getPackageName(), null); intent.setData(uri); startActivity(intent); } }) .show(); } } }
在这里,我曾经Snackbar
向用户显示有关Permission的相关消息,并且mainLayout
是id Activity's Main Layout
.
希望它能帮到你.