Android 6.0以上动态获取读写权限

原文:Link

修改 AndroidManifest.xml,以存储卡读写权限为例

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

在MainActivity中添加动态获取权限的代码
Step1:编写一个权限校验的方法

private void initPermission() {
        String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        ArrayList<String> 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);
    }

作者:RunningJiang
链接:https://www.jianshu.com/p/051f8d333152
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Leave a Reply