AndroidManifest.xml ↓
<!--加读写权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Java ↓
//定义请求码
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE" };
//然后通过一个函数来申请
public static void readWritePermission(Activity activity) {
try {
//检测是否有权限:permission = 0 ,则有权限
int permission = ActivityCompat.checkSelfPermission(activity,
"android.permission.WRITE_EXTERNAL_STORAGE");
//判断是否有权限,没有则弹出对话框
if (permission != PackageManager.PERMISSION_GRANTED) {
//Activity的实例、String数组、请求码
ActivityCompat.requestPermissions(activity, PERMISSIONS,REQUEST_EXTERNAL_STORAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//--------------在 onCreate中调用此函数--------------
readWritePermission(this);
效果图 ↓