Android:将简单文本共享为文件/附件 [英] Android: share simple text as file/attachment
问题描述
我有一个可以收集一些信息并允许用户使用Android的Intent框架共享它的应用.
I have an app that collects some info and allows the user to share it using Android's Intent framework.
到目前为止,它以纯文本形式共享报告:使用putExtra(Intent.EXTRA_TEXT, report)
,其中report
是String
.
So far, it shares the report as plain text: using putExtra(Intent.EXTRA_TEXT, report)
, where report
is a String
.
但是,我希望将报告以文件形式共享,从而使其更易于以电子邮件附件而不是正文的形式共享.
However, I want the report to be shared as a file, making it easy to share as an email attachment rather than the body.
我是否必须为此目的创建一个实际文件?如果这样做,它必须位于其他应用程序可以读取的位置,如发送二进制内容.
Do I have to create an actual file for that purpose? If I do, it has to be in a location that other apps can read, as explained in send binary content.
我期待一个可以提供ByteArrayOutputStream
的API,所以也许我只是缺少了一些东西.具体来说,我不想强迫共享应用程序获得对任何存储的许可.
I was expecting an API that would allow me to provide a ByteArrayOutputStream
, so maybe I'm just missing something. Specifically, I'd rather NOT force the sharing app to get permission to any storage.
推荐答案
使用设置文件共享,以获取简短的教程.
Use FileProvider
to share a file that is not publicly accessible. Check out Setting Up File Sharing for a short tutorial.
将文本作为电子邮件附件发送虽然有点棘手.您不能使用text/plain
作为类型,因为这意味着数据在EXTRA_TEXT
中提供.但是这些额外的文字最终会出现在电子邮件正文中,而不是附件中.
Sending text as an email attachment is a bit tricky though. You can't use text/plain
as type because that would imply the data is supplied in EXTRA_TEXT
. But text in this extra will end up in the email body, not in an attachment.
以下是可行的方法:
Uri fileUri = FileProvider.getUriForFile(context, "org.example.provider.authority", reportFile);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
startActivity(Intent.createChooser(shareIntent, null));
您还应该确保FileProvider.getType()
返回报告文件的text/plain
.最简单的方法是使用.txt
作为文件扩展名,而FileProvider
将自动执行正确的操作.
You should also make sure that FileProvider.getType()
returns text/plain
for the report file. The easiest way to accomplish this is by using .txt
as file extension and FileProvider
will automatically do the right thing.
这篇关于Android:将简单文本共享为文件/附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!