17

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"));
Cœur
  • 37,241
  • 25
  • 195
  • 267
Renjith Krishnan
  • 2,446
  • 5
  • 29
  • 53

5 Answers5

24

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 */*

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
10

To keep your code pragmatic, use ShareCompat class:

ShareCompat.IntentBuilder.from(this)
        .setStream(uri)
        .setType(URLConnection.guessContentTypeFromName(file.getName()))
        .startChooser();
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
2

This will help you

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"));
Hemant N. Karmur
  • 840
  • 1
  • 7
  • 21
  • By using this as-is, you will get `FileUriExposedException` when targeting SDK 24 >. Instead, you should be using a `FileProvider` instead of passing the `Uri` directly. – HB. Apr 22 '20 at 06:15
  • for this exception FileUriExposedException add this code in your main activity under onCreate method. StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); – Raj Bedi Oct 11 '20 at 10:50
0

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

hn_tired
  • 690
  • 10
  • 21
0
public void ShareFile(String path)
{
    Intent shareToneIntent=new Intent(Intent.ACTION_SEND);
    shareToneIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
    shareToneIntent.setType(GetMimeType(Uri.parse(path)));
    requireContext().startActivity(shareToneIntent);
}

public String GetMimeType(Uri uri) {
    String mimeType = null;

    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        mimeType = requireContext().getContentResolver().getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
    }
    return mimeType;
}
Kaarthikeyan
  • 500
  • 5
  • 12