如何以编程方式在Android中共享文件

如何以编程方式在Android中共享文件,android,share,Android,Share,我想使用共享意图共享一个文件(.pdf、.apk等),我搜索了谷歌,但只找到了共享图像的代码 Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.parse(path); sharingIntent.setType("image/png"); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); startActivity(I

我想使用共享意图共享一个文件(.pdf、.apk等),我搜索了谷歌,但只找到了共享图像的代码

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"));

使用相同的代码,只需更改要共享的数据类型的MIME类型。如果您希望共享任何内容,而不考虑类型,请使用
*/*

为保持代码的实用性,请使用
ShareCompat
类:

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

对于sdk 24及更高版本,如果需要获取应用程序存储外部文件的Uri,则会出现此错误

android.os.FileUriExposedException: file:///storage/emulated/0/MyApp/Camera_20180105_172234.jpg exposed beyond app through ClipData.Item.getUri()
要解决此问题:

这将帮助您

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

谢谢你的回答,你救了我的一天。按原样使用,你将在瞄准SDK 24>时获得
FileUriExposedException
。相反,您应该使用
FileProvider
而不是直接传递
Uri
。对于此异常,FileUriExposedException将此代码添加到onCreate方法下的主活动中。StrictMode.VmPolicy.Builder=新的StrictMode.VmPolicy.Builder();StrictMode.setVmPolicy(builder.build());这项工作和我们的一切,爱kotlin