我需要打开图库以在特定目录中显示图像,在我按照此搜索后进行搜索 How to open gallery to show images in a specific directory
但是file.list在android 4.4上返回一个null String [] 比我写一些测试代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listDirectory("ExternalStorageRoot",
Environment.getExternalStorageDirectory());
listDirectory(
"DCIM",
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
writeFileTest();
}
private void writeFileTest() {
String tag = "WriteTest";
String path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath();
path = path + "/testFile.txt";
Log.d(tag, "path : " + path);
File file=new File(path);
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write("THIS IS A TEST LINE".getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void listDirectory(String tag, File f) {
Log.d(tag, "absolute path " + f.getAbsolutePath());
Log.d(tag, "is dir " + f.isDirectory());
Log.d(tag, "can read " + f.canRead());
Log.d(tag, "can write " + f.canWrite());
String[] fileNames = f.list();
Log.d(tag, fileNames == null ? "fileNames is null"
: "fileNames is not null");
if (fileNames != null) {
for (String string : fileNames) {
Log.d(tag, "file -- " + string);
}
}
}
我还在AndroidManifest.xml中添加了这些行
<permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
TO:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
编辑: 我搞砸了这个许可。现在一切都运转正常!
答案 0 :(得分:2)
4.4更改了SD卡的文件权限。你不能再写在个人目录之外了。另见:http://www.androidcentral.com/kitkat-sdcard-changes