我正在使用以下代码尝试列出下载目录中的文件。
我构建了apk,将其安装在我的手机上,然后运行它。当我在手机的文件浏览器中查看时,我在内存/下载文件夹和外部存储器/下载文件夹中都有文件,但应用程序不显示文件列表。当我调试时,我发现listFiles()
函数返回null
。
请让我知道我做错了什么。变量state
已安装值,因此该问题与未安装的内存无关。
String state = Environment.getExternalStorageState();
private boolean isMediaAvailable() {
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
} else {
return false;
}
}
if (!isMediaAvailable()) {
Utility.finishWithError(this,"Media Not Available");
} else {
String path =Environment.getExternalStorageDirectory().toString()+ File.separator + Environment.DIRECTORY_DOWNLOADS;
File file = new File(path);
mRootPath = file.getAbsoluteFile().getPath();
mFileNames = new ArrayList<String>();
File filesInDirectory[] = file.listFiles();
if (filesInDirectory != null) {
for (int i = 0; i<filesInDirectory.length;i++) {
mFileNames.add(filesInDirectory[i].getName());
}
}
}
答案 0 :(得分:8)
使用:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
获取下载的目录,
并使用File.list()获取包含目录中文件列表的数组。
答案 1 :(得分:3)
向项目清单文件添加存储权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
并要求用户授予这样的权限:
int PERMISSION_ALL = 1; String [] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
将此方法添加到您的代码中:
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
并且可以覆盖它:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Toast.makeText(getApplicationContext(), "permission was granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
现在您可以使用以下代码访问您的应用程序下载目录:
context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
祝你好运:)