How to share *.txt file in android

2020-07-11 06:05发布

问题:

I tried many ways but i can't do this .

I have a *.txt file . i want share it via Bluetooth , wifi , email and ... .

When i used this code i cant share the file:

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

Totally i want this : when user clicked on share button and choose one email sender like Gmail for sharing . the file must be attached file for new email ...

I found this link https://stackoverflow.com/a/16036249/4016922

But it share txt file content . i want to share file not content of txt file

回答1:

Change your Code Like this.

From

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

To

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

from:

sharingIntent.setType("*/txt");

To

sharingIntent.setType("text/*");

so yourFinal Code Looks Like

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