How to share a file in Android programmatically

守給你的承諾、 提交于 2019-11-29 02:53:23

问题


I want to share a file(.pdf,.apk etc) using share Intent, I searched google but I find only the code for sharing Image

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

回答1:


You use the same code, you just change the MIME type for the type of data you wish to share. If you wish to share anything regardless of type, use */*




回答2:


To keep your code pragmatic, use ShareCompat class:

ShareCompat.IntentBuilder.from(this)
        .setStream(uri)
        .setType(URLConnection.guessContentTypeFromName(file.getName()))
        .startChooser();



回答3:


For sdk 24 and up, if you need to get the Uri of a file outside your app storage you have this error.

android.os.FileUriExposedException: file:///storage/emulated/0/MyApp/Camera_20180105_172234.jpg exposed beyond app through ClipData.Item.getUri()

to fix this : exposed beyond app through ClipData.Item.getUri



来源:https://stackoverflow.com/questions/23026776/how-to-share-a-file-in-android-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!