简体   繁体   中英

How to create a share button for whatsapp, facebook or others app installed in my phone

I am developing an app, where I want to share the TEXT and IMAGE to other apps installed on my phone. But when I click the share button Neither it shares TEXT nor IMAGE just empty it directs me to another app I chose for sharing. below postDescription and postImage are my methods of model class, and I checked that am I getting values are not in a toast it gives there values properly.

Below is the code:

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                shareIntent.setType("image/*");
                shareIntent.putExtra(Intent.EXTRA_TEXT, postDescription);

                Uri uri = Uri.parse(postImage);
                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                context.startActivity(Intent.createChooser(shareIntent, "Share With"));

So the above bunch of code was not working, then I found code through which I can share my post TEXT and IMAGE to WhatsApp only, I tried that but it shows file formate not supported inside WhatsApp.

below is the code for sharing to WhatsApp only:

  Uri imgUri = Uri.parse(postImage);
            Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
            whatsappIntent.setType("text/plain");
            whatsappIntent.setPackage("com.whatsapp");
            whatsappIntent.putExtra(Intent.EXTRA_TEXT, postDescription );
            whatsappIntent.putExtra(Intent.EXTRA_STREAM, imgUri);
            whatsappIntent.setType("image/jpeg");
            whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                context.startActivity(whatsappIntent);
            } catch (android.content.ActivityNotFoundException ex) {

                Toast.makeText(context, "Whatsapp have not been installed.", Toast.LENGTH_SHORT).show();
            }

I want to know how to create a share button that works fine for WhatsApp and everything or only WhatsApp will do the work for me.

By removing the package from the intent, Android should display the list of apps that can handle the type of intent.

Uri imgUri = Uri.parse(postImage); //Provide the URI to the downloaded image, not an external URL
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("*/*");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, postDescription );
whatsappIntent.putExtra(Intent.EXTRA_STREAM, imgUri);
if (whatsappIntent.resolveActivity(packageManager) != null) {
    startActivity(whatsappIntent)
}

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