我正在编写一个 Android 应用程序,并试图将位图保存到外部存储器中。 我的代码如下。
ContentValues contents = new ContentValues();
String curTime = AppSetting.currentDateString();
contents.put("title", curTime);
contents.put("display_name", curTime);
contents.put("description", curTime);
contents.put("datetaken", Long.valueOf(System.currentTimeMillis()));
contents.put("mime_type", "image/jpeg");
String path = Environment.getExternalStorageDirectory().toString() + "/dcim/camera";
String hashPath = String.valueOf(path.hashCode());
String displayName = (new File(path)).getName().toLowerCase();
contents.put("bucket_id", hashPath);
contents.put("bucket_display_name", displayName);
Uri uri = this.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, contents);//this is always null!!!
BufferedOutputStream oStream = new BufferedOutputStream(this.getContentResolver().openOutputStream(uri));
bmp.compress(CompressFormat.JPEG, 100, oStream);
oStream.close();
但 uri 始终为 null。
在做一些研究时,我发现消息来源表明这是因为 Activity 被破坏并重新创建。为了解决这个问题,我将上面的代码添加到 Activity 的 OnCreate() 中,但我仍然得到相同的结果。
我测试了几个 Android 设备,但 uri 始终为空。
有什么建议吗?
最佳答案
我发现了我的问题。
我用以下宏替换了显示名称,它起作用了。
MediaStore.Images.ImageColumns.DISPLAY_NAME
结果我发现这不是“display_name”,它有下划线前缀:“_display_name”。
希望这可以帮助。
关于Android 将图像保存到外部存储,但 ContentResolver.insert 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21095971/