如何在安卓设备上分享*.txt文件

8
我尝试了许多方法,但是我无法做到这一点。
我有一个* .txt文件。 我想通过蓝牙、wifi、电子邮件等方式共享它。
当我使用这段代码时,我无法分享文件:
  File file = new File(Environment.getExternalStorageDirectory(), "Email-Ghap/Emails.txt");
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("*/txt");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, file);
        startActivity(Intent.createChooser(sharingIntent, "share file with"));

当用户点击分享按钮并选择一个电子邮件发送者(如Gmail)进行分享时,我希望文件能够作为新电子邮件的附件。我找到了这个链接https://dev59.com/wXDYa4cB1Zd3GeqPGf-p#16036249,但它只分享txt文件内容,我想分享文件而不是txt文件的内容。

尝试使用以下链接: 共享PDF文件,您可以将其更改为.txt格式 https://dev59.com/H2Ml5IYBdhLWcg3w966L - Chetan Joshi
1个回答

13

请将您的代码更改为以下内容。

来自

File file = new File(Environment.getExternalStorageDirectory(), "Email-Ghap/Emails.txt");

File file = new File(Environment.getExternalStorageDirectory() + "/" + "Email-Ghap/Emails.txt");

发件人:

sharingIntent.setType("*/txt");

sharingIntent.setType("text/*");

那么你的最终代码看起来像这样

    File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "abc.txt");
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/*");
            sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
            startActivity(Intent.createChooser(sharingIntent, "share file with"));

谢谢,但是这无法发送文件。蓝牙和其他共享方法出现了,但当我选择它们发送时,什么也没发生。 - SAYE
当我使用这个代码 File file = new File(Environment.getExternalStorageDirectory() + "/" + "Email-Ghap/Emails.txt"); 并在日志中打印 file 时,它并不是正确的地址。我认为我的查找路径的方式是正确的:File file = new File(Environment.getExternalStorageDirectory(), "Email-Ghap/Emails.txt"); - SAYE
实际上,我从同一段代码中成功发送了我的文件。 - Learning Always
你是在发送一个 *.txt 文件吗?你能成功地通过蓝牙发送吗? - SAYE
让我们在聊天中继续这个讨论 - Learning Always
Uri.parse在调用“parse”时出现错误:错误:找不到符号方法parse(String),我该怎么办? - Bay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接