注意:下面的SO链接中有类似的问题,但是提出的解决方案都不适用于我,因此我开始了这个讨论。
问题陈述: 我正在从URL下载图像,然后尝试分享相同的图像。为了实现这一目标,我需要Uri,我通过将图像保存在MediaStore.Images.Media中获得。
代码:
A. 从AsyncTask类获取已下载的图像
public void processDownloadedImage(Bitmap bitmap) {
if (bitmap == null) {
Toast.makeText(this,"Image could not be downloaded and shared!",Toast.LENGTH_LONG).show();
}
else {
downloadedImage = bitmap;
checkPermissionShowShareSheet();
}
}
B. 检查 Marshmallow 及更高版本的权限
public void checkPermissionShowShareSheet() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)){
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},2909);
}
else {
updateImageUri(downloadedImage);
showShareSheet(downloadedImageUri);
}
}
else {
updateImageUri(downloadedImage);
showShareSheet(downloadedImageUri);
}
}
获取图像 URI
private void updateImageUri(Bitmap inImage){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
fixMediaDir();
String path = MediaStore.Images.Media.insertImage(this.getContentResolver(), inImage, "SomeImage", null);
storePathInSharedPreferences(path);
Uri uri = Uri.parse(path);
downloadedImageUri = uri;
}
void fixMediaDir() {
File sdcard = Environment.getExternalStorageDirectory();
if (sdcard != null) {
File mediaDir = new File(sdcard, "DCIM/Camera");
if (!mediaDir.exists()) {
mediaDir.mkdirs();
}
}
}
D.清单文件使用权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
问题:下面一行返回的值为空
String path = MediaStore.Images.Media.insertImage(this.getContentResolver(), inImage, "SomeImage", null);
有什么想法吗?
这是Stackbacktrace的一部分:
Failed to insert image java.io.FileNotFoundException: No such file or directory
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
at android.content.ContentProviderProxy.openAssetFile(ContentProviderNative.java:620)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:939)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:686)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:662)
at android.provider.MediaStore$Images$Media.insertImage(MediaStore.java:934)
at myorg.myapp.ImageDescription.updateImageUri(ImageDescription.java:165)