我设法listFiles()
在 Android 10 上使用文件,如下所示:
将此权限添加到项目的 AndroidManifest.xml 文件中:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在此文件中,android:requestLegacyExternalStorage="true"
在您的<application>
标签下添加标志。
向您的用户请求 READ_EXTERNAL_STORAGE 权限:
int PERMISSION_REQUEST = 1;
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST);
}
(可选)处理请求的结果:
@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, Do the you need to do.
Toast.makeText(getApplicationContext(), "permission was granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, Disable the functionality that depends on this permission.
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
然后,您可以使用listFiles()
,例如列出手机下载目录中的文件:
File[] files = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).listFiles();
Log.i(getClass().getName(), "fileList = " + Arrays.toString(files));