我尝试通过此程序从外部存储中获取文件:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
StringBuilder builder = new StringBuilder();
File specFile = Environment.getExternalStorageDirectory();
builder.append(Environment.getExternalStorageState() + "\n");
if (specFile.exists()) {
builder.append(specFile);
if (specFile.list() != null) {
String[] files = specFile.list();
for (int i = 0; i < files.length; i++) {
builder.append(files[i] +"\n");
}
} else {
builder.append(" exist but empty\n");
}
}
builder.append("/storage/emulated/0/Android exist: " + new File("/storage/emulated/0/Android").exists());
textView.setText(builder);
}
}
已添加此权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
它在模拟器中效果很好,但是在真实电话中,当我尝试获取列表时它返回null。通常,它也可以在存储中找到目录。
答案 0 :(得分:0)
通过添加以下代码解决了问题:
int requestCode = 0;
if (Build.VERSION.SDK_INT >= 23) {
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode);
}
}