简体   繁体   中英

Share pdf file via whatsapp from my app on Android

I am try to send pdf file from my app to whatsapp, and here is the code, but something missing!!

it opens whatsapp and i can choose a contact but it says "sharing failed"!

the code

String PLACEHOLDER = "file:///android_asset/QUOT_2016_10(test).pdf";
File f = new File(PLACEHOLDER);
Uri uri = Uri.fromFile(f);

Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_TEXT, "hi");
share.setPackage("com.whatsapp");

share.putExtra(Intent.EXTRA_STREAM, uri);
share.setType("application/pdf");

activity.startActivity(share);

I figured out the problem, and here is the answer if somebody had the same issue. The problem was that I am trying to open the pdf from the asset folder which did n't work, and if would try to open the pdf from the download folder for example, it would work. Please refer to the the code below for the final correct way:

File outputFile = new File(Environment.getExternalStoragePublicDirectory
        (Environment.DIRECTORY_DOWNLOADS), "ref Number from Quotation.pdf");
Uri uri = Uri.fromFile(outputFile);

Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType("application/pdf");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setPackage("com.whatsapp");

activity.startActivity(share);                                                
 File outputPath= new File(Environment.getExternalStorageDirectory() + "/MyPdf/example.pdf");//change with your path

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("application/pdf");
    Uri fileUri = FileProvider.getUriForFile(getApplicationContext(),
            getPackageName() + ".fileprovider", outputPath);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
    startActivity(Intent.createChooser(shareIntent, "Share it"));

It's technically wrong, what if someone has WhatsApp business or want to share file on gmail then use this...

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, _text);
shareIntent.putExtra (Intent.EXTRA_STREAM, Uri.parse(_file));
startActivity(Intent.createChooser( shareIntent, "Share"));

In this u just have to add text and file Text u attach will become subject in gmail and if you are sharing image on WhatsApp then text will become as image caption

此代码给出错误“不支持文件格式”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM