【安卓笔记】android申请储存权限,读写文件

首先在AndroidManifest.xml中注册读取USB存储设备中的内容


    <!-- 读取您的USB存储设备中的内容 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <!-- 修改或删除您的USB存储设备中的内容 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    

检查权限

private void checkPermission() {
        try {
            String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_CODE);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

调用方法

checkPermission();

返回后生命周期的回调,可判断是否申请成功

private static final int REQUEST_CODE = 1;
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            //拒绝
            } else {
            
            }
        }
    }

你可能感兴趣的:(安卓笔记,android,java)