我在将图像从我的应用程序共享到 WhatsApp 时遇到问题。
int imageId = getResources().getIdentifier("image_name", "drawable", getPackageName());
Uri imageUri = Uri.parse("android.resource://com.companyname.packagename/drawable/"+ imageId);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
此代码适用于 Facebook Messenger 或内置 Messenger 的 Android。
但它不适用于 WhatsApp。我收到此错误消息:
“不支持文件格式!”
I've solved this problem by using @CommonsWare solution: https://github.com/commonsguy/cwac-provider
最佳答案
即使在 Android 11 上,这对我也有用。它基于以下 Android 文档:https://developer.android.com/training/data-storage/shared/media .在我的用例中,我需要共享通过将布局转换为位图而生成的图像。我必须首先将图像保存到共享媒体存储中,但我相信私有(private)存储也应该可以工作。
public void shareImage(Bitmap bitmap) {
Uri contentUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentResolver contentResolver = getApplicationContext().getContentResolver();
ContentValues newImageDetails = new ContentValues();
newImageDetails.put(MediaStore.Images.Media.DISPLAY_NAME, "filename");
Uri imageContentUri = contentResolver.insert(contentUri, newImageDetails);
try (ParcelFileDescriptor fileDescriptor =
contentResolver.openFileDescriptor(imageContentUri, "w", null)) {
FileDescriptor fd = fileDescriptor.getFileDescriptor();
OutputStream outputStream = new FileOutputStream(fd);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bufferedOutputStream);
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException e) {
Log.e(TAG, "Error saving bitmap", e);
}
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, imageContentUri);
sendIntent.putExtra(Intent.EXTRA_TEXT, "some text here");
sendIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.setType("image/*");
Intent shareIntent = Intent.createChooser(sendIntent, "Share with");
startActivity(shareIntent);
}
关于Android 分享图片 Intent : WhatsApp - The file format is not supported,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37833459/