Android sharing image doesn't work

馋奶兔 提交于 2019-12-05 06:47:24

First, never use concatenation to build file paths, let alone Uri values.

Second, EXTRA_STREAM is supposed to hold a Uri, not a String.

Third, since you know the right MIME type (image/png), use it, instead of a wildcard.

Fourth, never build the same path twice. Here you create File image the right way, then ignore that value.

So, dump the String url line, replace image/* with image/png, and modify:

sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, url);

to be:

sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(file));

Also, consider using the android.support.v4.content.FileProvider class to share your file using a content URI instead of a file URI. It's more secure. See the reference documentation for FileProvider

You need to pass Content URI all the time (at least in Android 5.1+). here's how to get a content path from a Bitmap :

Bitmap bitmap;//this should be your bitmap
String MediaFilePath = Images.Media.insertImage(MainActivity.getContentResolver(), bitmap, FileName, null);

And then to share :

public static void ShareFile(String ContentPath, String Mime)
    {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);

        sharingIntent.setType(Mime);

        Uri FileUri = Uri.parse( ContentPath );


        sharingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, FileUri);

        MainActivity.startActivity(Intent.createChooser(sharingIntent, "Share to..."));
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!