美文网首页
基于PermissionsDispatcher兼容高版本运行时权

基于PermissionsDispatcher兼容高版本运行时权

作者: Endeav0r | 来源:发表于2018-07-23 11:52 被阅读454次

步骤:

1.PermissionsDispatcher导包
implementation "com.github.hotchemi:permissionsdispatcher:2.1.3"
annotationProcessor "com.github.hotchemi:permissionsdispatcher-processor:2.1.3"
2.添加注解
PermissionsDispatcher.png
@RuntimePermissions
public class MineFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        Button btn = view.findViewById(R.id.call);
        btn.setOnClickListener(onClickListener);
        return view;
    }

    private View.OnClickListener onClickListener = v ->
     MineFragmentPermissionsDispatcher.callWithCheck(MineFragment.this);


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MineFragmentPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }

    // permissions.dispatcher.processor.exception.PrivateMethodException:
    // Method 'call()' annotated with '@NeedsPermission' must not be private
    // 方法不能是private的
    @NeedsPermission({Manifest.permission.CALL_PHONE,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void call() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + "10086"));
        startActivity(intent);
    }

    // 第一次拒绝后 之后再次申请 弹出的说明
    @OnShowRationale({Manifest.permission.CALL_PHONE,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showWhy(final PermissionRequest request) {
        new AlertDialog.Builder(getActivity())
                .setMessage("说明:你必须给权限才能正常运行")
                .setPositiveButton("立即允许", (dialog, which) -> request.proceed())
                .show();
    }

    // 拒绝回调
    @SuppressLint("WrongConstant")
    @OnPermissionDenied({Manifest.permission.CALL_PHONE,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDenied() {
        Toast.makeText(getActivity(), "你拒绝了权限请求", 0).show();
    }

    // 拒绝----永不提醒回调
    @OnNeverAskAgain({Manifest.permission.CALL_PHONE,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void never() {
        Toast.makeText(getActivity(), "权限拒绝", 0).show();
    }
}
3.build-make project生成辅助类

MineFragmentPermissionsDispatcher:可在...\build\intermediates\classes\debug\com\es.....相应包下查看,该类中会生成两个方法callWithCheck,检查权限与调用方法,onRequestPermissionsResult请求权限回调结果处理。

注意:为了看清步骤,上面的代码是完整代码,这里两个方法调用要在生成辅助类之后。

4.运行效果图

第一次申请(多个权限)


1.png 2.png

拒绝其中一个后再次申请说明:


3.png

再次申请:


4.png
补充:可以在闪屏页进行全部权限的申请

相关文章

网友评论

      本文标题:基于PermissionsDispatcher兼容高版本运行时权

      本文链接:https://www.haomeiwen.com/subject/pjgdmftx.html