How can I send message to specific contact through WhatsApp from my android app?
Asked Answered
C

13

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.

Cardialgia answered 31/3, 2016 at 22:25 Comment(3)
Check out the FAQPodagra
Opening up specific contact in whatsapp through intent is not supported till now.Dagall
@Johny Moo Are you able to send message to particular contact?Mcswain
J
-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.

Jessjessa answered 31/3, 2016 at 22:38 Comment(9)
I tried your code and it works fine, but i need select the contact automatically.Cardialgia
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.Jessjessa
i am using ACTION_SENDTO, i think that the parameter was change,Cardialgia
Yeah, you're out of luck then.Jessjessa
The question says: " I need to send a message to specific contact from WhatsApp". So why is this the accepted answer?Quartz
i think because the owner of the question didn't need any help anymore.Unwieldy
no if you try code of question's owner then it works well but only pre text not sending yetDismay
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!!Dismay
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 workingBellerophon
H
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.

Harlamert answered 27/10, 2016 at 13:0 Comment(12)
Its open particular whasts app chat, but not send message.Malenamalet
This is kind of a hack, you're matching the internal intent scheme used by whatsapp to start its own activity. It's genius, but at the same time developers should not attempt change the default behaviour of the target app that is supposed to process the data. Users are used to choosing contact when whatsapp starts and thats ok.Labium
Is it a valid way to send "message" to specific contact in whatsapp programmatically??Greave
@Antoine Yeah approximately .It will open the chat activity of selected user with the message passed through intent .Harlamert
@RishabhMaurya is it possible to add the text's message?Ringler
@Ringler This is the best I got !Harlamert
@RishabhMaurya will this work for directly sharing images like text messages?Ineducation
@RishabhMaurya its working for images as well. I just commented the code // .setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));Ineducation
what about the button to be clicked? can the code do that as expected?Unwieldy
@RishabhMaurya can we send videos or pdf instead message to specific contact through app automically on schedule ?Vivisectionist
@RishabhMaurya I want to send image and text to unsaved numbers.Claypan
@ManjunathGk Is there any app available which can do that?Harlamert
R
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
Raynor answered 8/11, 2017 at 18:55 Comment(0)
B
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!

Barrows answered 22/8, 2017 at 15:39 Comment(4)
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?Sellers
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.Barrows
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?Sellers
I´m not sure about that, but if you can achieve it, let us know pls :)Barrows
I
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!

Ineducation answered 16/5, 2017 at 6:37 Comment(2)
this is best solution till now.. @Shail if you get solution to send without pressing send button please le me informBryonbryony
It opens a blank chatbox, how to add a message?Claypan
S
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();
    }
}
Schaeffer answered 10/4, 2018 at 11:43 Comment(0)
A
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);
Absorbefacient answered 24/8, 2018 at 6:41 Comment(0)
R
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);
Ronald answered 15/1, 2017 at 19:54 Comment(0)
B
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

Battalion answered 16/3, 2017 at 12:3 Comment(0)
E
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));
Ethnogeny answered 11/10, 2018 at 4:40 Comment(0)
M
0
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW); 
String url ="https://wa.me/your number"; 
sendIntent.setData(Uri.parse(url));
startActivity(sendIntent);
Mousetail answered 12/12, 2018 at 11:47 Comment(0)
A
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())
    }
Alysiaalyson answered 9/1, 2019 at 10:31 Comment(0)
W
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");
    }
Wacky answered 18/4, 2023 at 16:10 Comment(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.Monomerous
J
-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.

Jessjessa answered 31/3, 2016 at 22:38 Comment(9)
I tried your code and it works fine, but i need select the contact automatically.Cardialgia
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.Jessjessa
i am using ACTION_SENDTO, i think that the parameter was change,Cardialgia
Yeah, you're out of luck then.Jessjessa
The question says: " I need to send a message to specific contact from WhatsApp". So why is this the accepted answer?Quartz
i think because the owner of the question didn't need any help anymore.Unwieldy
no if you try code of question's owner then it works well but only pre text not sending yetDismay
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!!Dismay
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 workingBellerophon

© 2022 - 2024 — McMap. All rights reserved.