您好我正在编写应用程序,其中一个功能是读取下载的数据,我想获取android / emulated / 0 / Download包含的所有文件。我知道它是一个内部存储,我在Manifest文件中只有外部存储权限,我不知道如何添加从这个目录读取数据的权限。
ArrayList<String> files = findURs(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), new ArrayList<String>());
这段代码是由另一位用户编写的,但我只是编辑了它
public ArrayList findURs(File dir,ArrayList matchingURFileNames){ String safPattern =“。ur”;
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
findURs(listFile[i], matchingURFileNames);
} else {
if (listFile[i].getName().endsWith(safPattern)) {
matchingURFileNames.add(dir.toString() + File.separator + listFile[i].getName());
}
}
}
}
return matchingURFileNames;
}
答案 0 :(得分:1)
首先像这样进行运行时permision检查,
private int REQUEST_CODE = 100;
private static String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void checkPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE);
} else {
ArrayList<String> files = findURs(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), new ArrayList<String>());
}
}
处理您的权限结果,
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ArrayList<String> files = findURs(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), new ArrayList<String>());
}
}
}
同时添加清单
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />