我将于茫茫人海中访我唯一灵魂之伴侣;得之,我幸;不得,我命,如此而已。——徐志摩
安卓请求文件授权
在AndroidManifest.xml
中加上
1 2 3 4
| <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
在启动的activity
声明
1 2 3 4 5 6
| 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
| 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
| @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]); } } }
|