Android 6.0以上动态获取权限

君子赠人以言,庶人赠人以财。——荀况

  • 修改 AndroidManifest.xml,以存储卡读写权限为例
    
    
    
  • 在MainActivity中添加动态获取权限的代码

Step1:编写一个权限校验的方法

private void initPermission() {
        String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        ArrayList toApplyList = new ArrayList<>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(Objects.requireNonNull(this), perm))  {
                toApplyList.add(perm);
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 1);
        }
    }

Step2:在onCreate中调用

protected void onCreate(Bundle savedInstanceState) {
        //init face model at here
        initPermission();
        initFaceDetectModel();
        face_engine_obj = new FaceEngine();
        String re_turn = face_engine_obj.StartEngine("./models");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

你可能感兴趣的:(Android 6.0以上动态获取权限)