在我的mibox 4k更新到android oreo后,该应用程序无法运行
代码查找外部存储器
private String[] getUsbStoragePaths()
{
List<String> result = new ArrayList<>();
File storageDir = new File("/storage");
if(storageDir.isDirectory()) {
File[] subDir = storageDir.listFiles();
for(File dir : subDir) {
if(dir.canRead()) {
result.add(dir.getAbsolutePath());
}
}
}
return result.toArray(new String[0]);
}
private List<File> getSubDirs(String path) {
List<File> result = new ArrayList<>();
File root = new File(path);
if (root.exists() && root.canRead()) {
File[] subDirs = root.listFiles(); ->>>>>> alway null
if (subDirs !=null)
{
for(File dir: subDirs)
{
if (dir.isDirectory() && dir.canRead())
{
result.add(dir);
}
}
}
}
return result;
}
我的USB存储有子文件夹
根
--SUDRI1
--SUDRI2
--SUDRI3
--FILE1
应用程序中的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在运行时请求权限
private void requestStoragePermission() {
if (!hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
!hasPermission(, Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
private boolean hasPermission(final String permission) {
return PackageManager.PERMISSION_GRANTED == getApplicationContext().getPackageManager().checkPermission(
permission, getApplicationContext().getPackageName());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other things
requestStoragePermission();
}
getSubdirs方法的结果为空,
file[]subdirs=root.listfiles();—>>>>>始终为空
最佳答案
This code will give you files which are stored inside directory.
String pattern = ".png";
File directory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Your directory name");
File[] fileList = directory.listFiles();
if (fileList != null && fileList.length > 0) {
for (File file : fileList) {
//if you need particular file format than check with that otherwise remove it.
if (file.isFile() && file.getName().endsWith(pattern)) {
//
}
}
}