6

I am developing an android app and I need to send a message to specific contact from WhatsApp. I tried this code:

Uri mUri = Uri.parse("smsto:+999999999");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("sms_body", "The text goes here");
mIntent.putExtra("chat",true);
startActivity(mIntent);

The problem is that the parameter "sms_body" is not received on WhatsApp, though the contact is selected.

Johny Moo
  • 63
  • 1
  • 1
  • 6

13 Answers13

22

There is a way. Make sure that the contact you are providing must be passed as a string in intent without the prefix "+". Country code should be appended as a prefix to the phone number .

e.g.: '+918547264285' should be passed as '918547264285' . Here '91' in beginning is country code .

Note :Replace the 'YOUR_PHONE_NUMBER' with contact to which you want to send the message.

Here is the snippet :

 Intent sendIntent = new Intent("android.intent.action.MAIN");
 sendIntent.setComponent(new  ComponentName("com.whatsapp","com.whatsapp.Conversation"));
 sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"@s.whatsapp.net");
 startActivity(sendIntent);

Update:

The aforementioned hack cannot be used to add any particular message, so here is the new approach. Pass the user mobile in international format here without any brackets, dashes or plus sign. Example: If the user is of India and his mobile number is 94xxxxxxxx , then international format will be 9194xxxxxxxx. Don't miss appending country code as a prefix in mobile number.

  private fun sendMsg(mobile: String, msg: String){
    try {
        val packageManager = requireContext().packageManager
        val i = Intent(Intent.ACTION_VIEW)
        val url =
            "https://wa.me/$mobile" + "?text=" + URLEncoder.encode(msg, "utf-8")
        i.setPackage("com.whatsapp")
        i.data = Uri.parse(url)
        if (i.resolveActivity(packageManager) != null) {
            requireContext().startActivity(i)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

Note: This approach works only with contacts added in user's Whatsapp account.

Rishabh Maurya
  • 1,448
  • 3
  • 22
  • 40
7

This new method, send message to a specific contact via whatsapp in Android. For more information look here

            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_VIEW);
            String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + path;
            sendIntent.setData(Uri.parse(url));
            activity.startActivity(sendIntent);here
6

I found the right way to do this and is just simple after you read this article: http://howdygeeks.com/send-whatsapp-message-unsaved-number-android/

phone and message are both String.

Source code:

try {

    PackageManager packageManager = context.getPackageManager();
    Intent i = new Intent(Intent.ACTION_VIEW);

    String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
    i.setPackage("com.whatsapp");
    i.setData(Uri.parse(url));
    if (i.resolveActivity(packageManager) != null) {
        context.startActivity(i);
    }
} catch (Exception e){
    e.printStackTrace();
}

Enjoy!

Crono
  • 2,024
  • 18
  • 16
  • I've tried this code. It works but it's not exactly 'sending' it. It entered the text and now the user need to press 'send' button manually. Is it possible to just directly send it without waiting for the user to press the 'send' button? – Dante Jan 05 '18 at 15:30
  • It is not possible, because WhatsApp have his own privacy and security politycs and is being used by our applications through an intent, for that reason we can´t trigger the "send" button, we only can configure a message and contact to send it, but final users must have the last choice to "send" our automatic messages to their contacts. – Crono Jan 05 '18 at 15:49
  • I see. Is it alright if we simulate touch at that position (as whatsapp usually has 'send' button at the bottom right corner of the screen) if the user allows my app to (I can add an option if the app can directly send the message and the confirmation of the message and contact number will be done right in my app instead of whatsapp) ? I guess that doesn't go against whatsapp privacy policy. right? – Dante Jan 05 '18 at 16:06
  • I´m not sure about that, but if you can achieve it, let us know pls :) – Crono Jan 05 '18 at 16:12
5

Great hack Rishabh, thanks a lot, I was looking for this solution since last 3 years.

As per the Rishabh Maurya's answer above, I have implemented this code which is working fine for both text and image sharing on WhatsApp. I have published this in my android app, so if you want to see it live try my app Bill Book

Note that in both the cases it opens a whatsapp conversation (if toNumber exists in users whatsapp contact list), but user have to click send button to complete the action. That means it helps in skipping contact selection step.

For text messages

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);

For sharing images

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
context.startActivity(sendIntent);

Enjoy WhatsApping!

Pioneer
  • 1,530
  • 1
  • 11
  • 11
2

We can share/send message to whats app. Below is Sample code to send text message on Whats-app

  1. Single user
private void shareToOneWhatsAppUser(String message) {

    /**
     * NOTE:
     * Message is shared with only one user at a time. and to navigate back to main application user need to click back button
     */
    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);

    //Directly send to specific mobile number...
    String smsNumber = "919900990099";//Number without with country code and without '+' prifix
    whatsappIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix

    if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
        Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
        return;
    }

    startActivity(whatsappIntent);
}
  1. Multiple user
private void shareToMultipleWhatsAppUser(String message) {

    /**
     * NOTE:
     *
     * If want to send same message to multiple users then have to select the user to whom you want to share the message & then click send.
     * User navigate back to main Application once he/she select all desired persons and click send button.
     * No need to click Back Button!
     */

    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);

    if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
        Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
        return;
    }

    startActivity(whatsappIntent);
}

One more way to achieve the same

private void shareDirecctToSingleWhatsAppUser(String message) {

    /**
     * NOTE:
     * Message is shared with only one user at a time. and to navigate back to main application user need to click back button
     */

    //Directly send to specific mobile number...
    String smsNumber = "919900000000";//Intended user`s mobile number with country code & with out '+'

    PackageManager packageManager = getPackageManager();
    Intent i = new Intent(Intent.ACTION_VIEW);

    try {
        String url = "https://api.whatsapp.com/send?phone="+ smsNumber +"&text=" + URLEncoder.encode("Test Message!", "UTF-8");
        i.setPackage("com.whatsapp");
        i.setData(Uri.parse(url));
        if (i.resolveActivity(packageManager) != null) {
            startActivity(i);
        }
    } catch (Exception e){
        e.printStackTrace();
    }
}
Rupesh Yadav
  • 12,096
  • 4
  • 53
  • 70
2

you can use this code:

 Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
sendIntent.putExtra("jid", "9194******22" + "@s.whatsapp.net");// here 91 is country code
sendIntent.putExtra(Intent.EXTRA_TEXT, "Demo test message");
startActivity(sendIntent);
0

This is what works for me.

The parameter 'body' gets not red by the whatsapp app, use 'Intent.EXTRA_TEXT' instead.

By setting the 'phoneNumber' you specify the contact to open in whatsapp.

Intent sendIntent = new Intent(Intent.ACTION_SENDTO, 
       Uri.parse("smsto:" + "" + phoneNumber + "?body=" + encodedMessage));
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
Yoraco Gonzales
  • 727
  • 10
  • 18
0
Uri mUri = Uri.parse("smsto:+90000900000");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("chat",true);
startActivity(Intent.createChooser(mIntent, "Share with"));

Works great to send message to specific contact on WhatsApp from my android app

node_modules
  • 4,790
  • 6
  • 21
  • 37
0

Try this code

Uri uri = Uri.parse("smsto:" + "+6281122xxx");
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));

You can't put string directly on putExtra like this

i.putExtra(Intent.EXTRA_TEXT, "YOUR TEXT");

Change your code and get string from resource like this

i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));
0
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW); 
String url ="https://wa.me/your number"; 
sendIntent.setData(Uri.parse(url));
startActivity(sendIntent);
Caleb Kleveter
  • 11,170
  • 8
  • 62
  • 92
0

Here's my way to do it (more here):

First, if you want to be sure you can send the message, you can check if the person has a WhatsApp account on the address book:

@RequiresPermission(permission.READ_CONTACTS)
public String getContactMimeTypeDataId(@NonNull Context context, String contactId, @NonNull String mimeType) {
    if (TextUtils.isEmpty(mimeType) || !PermissionUtil.hasPermissions(context, Manifest.permission.READ_CONTACTS))
        return null;
    ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{Data._ID}, Data.MIMETYPE + "= ? AND "
            + ContactsContract.Data.CONTACT_ID + "= ?", new String[]{mimeType, contactId}, null);
    if (cursor == null)
        return null;
    if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    String result = cursor.getString(cursor.getColumnIndex(Data._ID));
    cursor.close();
    return result;
}

and if all seem well, you open it as if it's from the web:

            final String contactMimeTypeDataId = getContactMimeTypeDataId(context, contactId, "vnd.android.cursor.item/vnd.com.whatsapp.profile");
            if (contactMimeTypeDataId != null) {
                final String whatsAppPhoneNumber = PhoneNumberHelper.normalizePhone(phoneNumber);
                String url = "https://api.whatsapp.com/send?phone="+ whatsAppPhoneNumber ;
                intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
                intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
                .setPackage("com.whatsapp");
                startActivity(intent);
            }

You can also check if WhatsApp is even installed before of all of this (or remove the setPackage and check if any app can handle the Intent) :

        final PackageManager packageManager = context.getPackageManager();
        final ApplicationInfo applicationInfo = packageManager.getApplicationInfo("com.whatsapp", 0);
        if (applicationInfo == null)
           return;

EDIT: about preparing the Intent with the Uri, I think this way is better:

    @JvmStatic
    fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
//     example url: "https://api.whatsapp.com/send?phone=normalizedPhoneNumber&text=abc"
        val builder = Uri.Builder().scheme("https").authority("api.whatsapp.com").path("send")
        normalizedPhoneNumber?.let { builder.appendQueryParameter("phone", it) }
        message?.let { builder.appendQueryParameter("text", it) }
        return Intent(Intent.ACTION_VIEW, builder.build())
    }

or alternative (based on here):

    fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
//     example url: "https://wa.me/normalizedPhoneNumber&text=abc"
        val builder = Uri.Builder().scheme("https").authority("wa.me")
        normalizedPhoneNumber?.let { builder.appendPath(it) }
        message?.let { builder.appendQueryParameter("text", it) }
        return Intent(Intent.ACTION_VIEW, builder.build())
    }
android developer
  • 114,585
  • 152
  • 739
  • 1,270
0
I use this:

String url = "https://api.whatsapp.com/send?phone=" + phoneNo + "&text=" + message;
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    intent.setPackage(packageName);

    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        System.out.println("Error Message");
    }
S. Gabran
  • 11
  • 3
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 22 '23 at 04:52
-2

Try using Intent.EXTRA_TEXT instead of sms_body as your extra key. Per WhatsApp's documentation, this is what you have to use.

An example from their website:

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

Their example uses Intent.ACTION_SEND instead of Intent.ACTION_SENDTO, so I'm not sure if WhatsApp even supports sending directly to a contact via the intent system. Some quick testing should let you determine that.

Nathan Walters
  • 4,116
  • 4
  • 23
  • 37
  • I tried your code and it works fine, but i need select the contact automatically. – Johny Moo Mar 31 '16 at 22:50
  • Were you using `ACTION_SEND` or `ACTION_SENDTO`? If it's the latter, that means WhatsApp doesn't support that intent properly, and there's not much you can do about that. – Nathan Walters Mar 31 '16 at 22:52
  • i am using ACTION_SENDTO, i think that the parameter was change, – Johny Moo Mar 31 '16 at 23:13
  • Yeah, you're out of luck then. – Nathan Walters Mar 31 '16 at 23:49
  • 2
    The question says: " I need to send a message to specific contact from WhatsApp". So why is this the accepted answer? – Simon Apr 26 '17 at 10:34
  • i think because the owner of the question didn't need any help anymore. – gumuruh Aug 10 '18 at 07:38
  • no if you try code of question's owner then it works well but only pre text not sending yet – Nikul Vaghani Oct 07 '18 at 17:45
  • `Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_VIEW); String url = "https://api.whatsapp.com/send?phone=" + "+91 9999999999" + "&text=" + "text to be share"; sendIntent.setData(Uri.parse(url)); activity.startActivity(sendIntent);` *above code works well for me!!* – Nikul Vaghani Oct 07 '18 at 18:04
  • this is misleading and should not be an accepted answer. the accepted answer should me @hemant kamat answer below. I tried it and it's working – Dika Jan 05 '19 at 04:33