51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

安卓请求文件授权

我将于茫茫人海中访我唯一灵魂之伴侣;得之,我幸;不得,我命,如此而已。------徐志摩

安卓请求文件授权

AndroidManifest.xml中加上

|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 | hljs xml <!-- 往SDCard写入数据权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 从SDCard读入数据权限 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |

image-20201023205450636

在启动的activity声明

|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 5 6 | hljs java //读写权限 public static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; //请求状态码 public static int REQUEST_PERMISSION_CODE = 1; |

在下方onCreate里加上

|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 5 | hljs java if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE); } } |

最后重写onRequestPermissionsResult方法

|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 5 6 7 8 9 | hljs java @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION_CODE) { for (int i = 0; i < permissions.length; i++) { Log.i("MainActivity", "申请的权限为:" + permissions[i] + ",申请结果:" + grantResults[i]); } } } |

image-20201023205341141

赞(0)
未经允许不得转载:工具盒子 » 安卓请求文件授权