Sam Smith
Sam Smith

Reputation: 79

Android share via Intent not working,

I need to be able to send text to a whatsapp contact, stack overflow seems to unanimously agree that this works:

Uri uri = Uri.parse("smsto:" + "<number>"); 
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
sendIntent.putExtra(Intent.EXTRA_TEXT, "YOOOH");
// sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);

If .setType("text/plain"); is commented out, it just opens whatsapp to the chat of the number I gave it, but if I don't comment it out, nothing happens at all, any help appreciated.

Upvotes: 1

Views: 947

Answers (2)

QuokMoon
QuokMoon

Reputation: 4425

Look at this code snippet that one also handled case if user not installed whatsApp.

PackageManager pm=getPackageManager();
                try {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    String text = "YOUR TEXT HERE";
                    PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
                    //Check if package exists or not. If not then code
                    //in catch block will be called
                    intent.setPackage("com.whatsapp");
                    intent.putExtra(Intent.EXTRA_TEXT, text);
                    startActivity(Intent.createChooser(intent, "Share with"));

                } catch (PackageManager.NameNotFoundException e) {
                    Toast.makeText(MainActivity.this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                            .show();
                }

Upvotes: 0

Emdad Hossain
Emdad Hossain

Reputation: 387

change and add the last line remove the comment of sendIntent.setType

Uri uri = Uri.parse("smsto:" + "<number>"); 
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
sendIntent.putExtra(Intent.EXTRA_TEXT, "YOOOH");
sendIntent.setType("text/plain");

// this line helps to open the chooser dialog
startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share)));

Upvotes: 1

Related Questions