Google开源的EasyPermissions的思路非常清晰,对申请权限的各种状态都做了处理。
下面是我对其做的简单封装
- BaseActivity
public class BaseActivity extends AppCompatActivity implements PermissionUtils.PermissionCallbacks {
private static final String TAG = BaseActivity.class.getCanonicalName();
private static final int PERMANENTLY_DENIED_REQUEST_CODE = 428; // Magic code
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionGranted(int requestCode, List<String> perms) {
Log.d(TAG, perms.size() + " permissions granted.");
}
@Override
public void onPermissionDenied(int requestCode, List<String> perms) {
Log.e(TAG, perms.size() + " permissions denied.");
// 用户勾选了“不在询问”后
if (PermissionUtils.somePermissionsPermanentlyDenied(this, perms)) {
PermissionUtils.onPermissionsPermanentlyDenied(this,
getString(R.string.rationale),
getString(R.string.rationale_title),
getString(android.R.string.ok),
getString(android.R.string.cancel),
PERMANENTLY_DENIED_REQUEST_CODE);
}
}
}
在BaseActivity中实现了PermissionUtils.PermissionCallbacks接口,覆写了*onRequestPermissionsResult()方法,并在onPermissionDenied()*中对用户勾选不在询问的情况作了处理(进入应用-设置界面)
- BaseFragment
public class BaseFragment extends Fragment implements PermissionUtils.PermissionCallbacks{
private static final String TAG = BaseFragment.class.getCanonicalName();
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionGranted(int requestCode, List<String> perms) {
Log.d(TAG, perms.size() + " permissions granted.");
}
@Override
public void onPermissionDenied(int requestCode, List<String> perms) {
Log.e(TAG, perms.size() + " permissions denied.");
//此处不处理"不在询问"的状态,如果处理了会导致弹出两个Dialog
//统一在BaseActivity中做处理
}
}
BaseFragment同样实现了PermissionUtils.PermissionCallbacks接口,覆写了*onRequestPermissionsResult()*方法,但是并未处理不在询问的情况,在Activity中统一处理。
注意:实际使用时,需要在BaseFragment的
onPermissionDenied()
回调中对勾选“不再询问”进行处理。
如果存在Activity以及其包含的Fragment同时需要申请权限,则应该在Activity统一处理,防止弹出两个Dialog