139

Since I found some older posts, that tell that whatsapp doesn't support this, I was wondering if something had changed and if there is a way to open a whatsapp 'chat' with a number that I'm sending through an intent?

Manan Sharma
  • 631
  • 2
  • 14
  • 28
Diego
  • 4,011
  • 10
  • 50
  • 76
  • did you tried share action provider? – Basim Sherif Mar 19 '13 at 09:28
  • Sounds interesting, but how would that work. Can I share a string (phonenumber) and will it open whatsapp(or the chooser?) can you give a little example? – Diego Mar 19 '13 at 10:22
  • 2
    although there is ACTION_SENDTO intent in whatsapp, it is not executed (properly) hence it is not possible to do to a specific phone number [thats what i found] – Manan Sharma Apr 11 '14 at 20:56
  • 2
    Possible duplicate of [Send text to specific contact (whatsapp)](http://stackoverflow.com/questions/19081654/send-text-to-specific-contact-whatsapp) – Rishabh Maurya Nov 03 '16 at 02:59
  • i'm still looking forward attaching both image & text at the same time, but found no luck, sigh :( – gumuruh Aug 10 '18 at 07:36

26 Answers26

201

UPDATE Please refer to https://faq.whatsapp.com/en/android/26000030/?category=5245251

WhatsApp's Click to Chat feature allows you to begin a chat with someone without having their phone number saved in your phone's address book. As long as you know this person’s phone number, you can create a link that will allow you to start a chat with them.

Use: https://wa.me/15551234567

Don't use: https://wa.me/+001-(555)1234567

Example: https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

Original answer Here is the solution

public void onClickWhatsApp(View view) {
    
    PackageManager pm=getPackageManager();
    try {

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.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
        waIntent.setPackage("com.whatsapp");

        waIntent.putExtra(Intent.EXTRA_TEXT, text);
        startActivity(Intent.createChooser(waIntent, "Share with"));
        
   } catch (NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
   }  

}

Also see http://www.whatsapp.com/faq/en/android/28000012

Chintan Bawa
  • 1,376
  • 11
  • 15
Manan Sharma
  • 631
  • 2
  • 14
  • 28
  • 1
    How to integrate with messaging? so that the user can choose whatsapp or messaging – Srikanth Pai May 10 '13 at 11:06
  • 39
    if we already have the contact information is it possible to add the contact information and send message without having to touch on the contact to select and click ok to send ?? – user1492955 Jun 13 '13 at 07:02
  • 1
    refer to http://stackoverflow.com/questions/19081654/send-to-specific-contact-whatsapp?lq=1 – Manan Sharma Oct 24 '13 at 21:00
  • 4
    @MananMerevikSharma source doesn't lie (https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/content/Intent.java). Additionally, basic Java principle: an object lives until there are no longer any references to them. – JRomero May 11 '14 at 07:20
  • Hi, this solution is great, but I was wondering if anyone knows if it's possible to send a url link, and not just plain text. I tried doing that using EXTRA_HTML_TEXT, but it didn't work. Thanks! – n00b programmer Jun 28 '14 at 18:44
  • Can we attach video, image or audio using the intent? – Dheeraj Bhaskar Jul 09 '14 at 11:49
  • @dheeraj you may change the intent type – Manan Sharma Jul 10 '14 at 03:47
  • 1
    @MananMerevikSharma -1. It does not "turn to a null pointer". The else-part can never be reached. When WhatsApp is not installed, the Intent is still sent, but a Dialog opens saying that there's no matching app. This means you are not providing any way to check whether WhatsApp is installed or not. – 0101100101 Jul 25 '14 at 14:28
  • So, we can use something like this though above code rons perfectly fine List resInfo = getPackageManager().queryIntentActivities(waIntent, 0); if (!resInfo.isEmpty()) – Manan Sharma Sep 14 '14 at 20:58
  • When a package is not present, instead of that toast, a system dialog appears saying - "No app can perform this action". – Confuse Sep 22 '14 at 07:44
  • @AntiMatter this particular code is quiet old (more than a year) there is a little change in the stack execution I know that intent can not be in a null state. This is just up for reference (as per SOF manifesto) please feel free to modify/update the code with a better solution -Best Merevik – Manan Sharma Sep 22 '14 at 07:51
  • Code ref for API level 16 or previous : public void onClickWhatsApp(View view) { Intent waIntent = new Intent(Intent.ACTION_SEND); waIntent.setType("text/plain"); String text = "YOUR TEXT HERE"; waIntent.setPackage("com.whatsapp"); if (waIntent != null) { waIntent.putExtra(Intent.EXTRA_TEXT, text);// startActivity(Intent.createChooser(waIntent, "Share with")); } else { Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT) .show(); } } – Manan Sharma Sep 22 '14 at 08:36
  • It seems like ACTION_SEND_TO has been integrated by the Facebook people. – Manan Sharma Dec 09 '14 at 15:47
  • waIntent.putExtra(Intent.EXTRA_TEXT, text); is not filling the message for whatApp. but working for default messag. Can you please help. – M.S Feb 20 '15 at 13:34
  • Is it possible to sent message for new number by intent params? – Pramod Waghmare Apr 05 '18 at 11:16
  • I am not sure. The thing is for https://api.whatsapp.com/send?phone=15551234567 Whatsapp has intent filters to redirect it to the app hence intent is not required at all. – Manan Sharma Apr 05 '18 at 22:57
  • Will it be possible to send PDF using this method? – abhishek77in May 01 '19 at 06:26
72

With this code you can open the whatsapp chat with the given number.

void openWhatsappContact(String number) {
    Uri uri = Uri.parse("smsto:" + number);
    Intent i = new Intent(Intent.ACTION_SENDTO, uri);
    i.setPackage("com.whatsapp");  
    startActivity(Intent.createChooser(i, ""));
}
user2957782
  • 695
  • 5
  • 10
  • 5
    @user2957782 i followed this sir , but when i click on my button to start my whatsapp it says "No apps can perform this action " – arjun narahari Dec 11 '14 at 07:24
  • @VihaanVerma can you share how you got this to work? I implemented the same code against whatsapp version 2.11.56021 and I'm getting nothing... – Alamgir Mand Mar 10 '15 at 22:39
  • 1
    Checked, it sends me to all chat list, not to a specific number's chat window. – Darpan Nov 27 '15 at 12:13
  • If you remove the 'setPackage' it will take you directly to window, but you can't add any message there.. – Darpan Nov 27 '15 at 13:22
  • 9
    It works only when you have that number in your chat list or contacts list. – Anshul Tyagi Mar 10 '16 at 07:15
  • 1
    instead of `startActivity(Intent.createChooser(i, ""));` use `startActivity(i);` for directly open provided number chat. 1. Tested on Samsung J7 prime it's working. 2. number wasn't in my contact list neither in my chat list. 3. if number is not using whatsapp, a dialog box appearing asking me that would I like to invite that contact on whatsapp. I'think it is the best solution if you want to provide whatsapp contact support for your app users. – Muhammad Saqib Sep 17 '17 at 13:40
  • this one is not applicable for sending an image inside the message. – gumuruh Aug 10 '18 at 07:35
32

Simple solution, try this.

String phoneNumberWithCountryCode = "+62820000000";
String message = "Hallo";

startActivity(
    new Intent(Intent.ACTION_VIEW,
        Uri.parse(
            String.format("https://api.whatsapp.com/send?phone=%s&text=%s", phoneNumberWithCountryCode, message)
        )
    )
);
Partharaj Deb
  • 864
  • 1
  • 8
  • 22
Latief Anwar
  • 1,833
  • 17
  • 27
25

I found the following solution, first you'll need the whatsapp id:

Matching with reports from some other threads here and in other forums the login name I found was some sort of: international area code without the 0's or + in the beginning + phone number without the first 0 + @s.whatsapp.net

For example if you live in the Netherlands and having the phone number 0612325032 it would be 31612325023@s.whatsapp.net -> +31 for the Netherlands without the 0's or + and the phone number without the 0.

public void sendWhatsAppMessageTo(String whatsappid) {

Cursor c = getSherlockActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
        new String[] { whatsappid }, null);
c.moveToFirst();

Intent whatsapp = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
c.close();

 if (whatsapp != null) {

startActivity(whatsapp);      

} else {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
//download for example after dialog
                Uri uri = Uri.parse("market://details?id=com.whatsapp");
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    }

}
Diego
  • 4,011
  • 10
  • 50
  • 76
  • I'm trying this code but it tells me that getSherlockActivity() is undefined. how to fix this ?? – Eman87 Dec 05 '13 at 22:22
  • 2
    @Eman87 Diego is using Action Bar Sherlock, so the method. Get the scope of your activity in place of getSherlockActivity(). – Manan Sharma Dec 13 '13 at 17:58
  • @Eman87 remove getSherlockActivity() , after that code will work perfectly. – BeingMIAkashs Dec 17 '13 at 12:43
  • 4
    There is no point in `if (whatsapp != null)` as 2 lines above you did `Intent whatsapp = new Intent(...)`. – Carcamano Feb 25 '14 at 18:27
  • When this method is called,a number option is available like FileExplorer(OfficeReader/WordReader) along with WhatsApp option. But i want to get WhatsApp chosen as default...Any suggestions? – Syamantak Basu Jun 30 '14 at 16:38
  • 3
    This is good option to open chat window directly if the person is exist in Contacts. Is there a way to do the same for new number which is not exist in our contacts ? – MohammedYakub M. Nov 19 '14 at 05:31
  • 1
    You need to add `` permission in `AndroidManifest.xml` – Pratik Butani Apr 23 '15 at 19:37
17

This should work whether Whatsapp is installed or not.

boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
if (isWhatsappInstalled) {
    Uri uri = Uri.parse("smsto:" + "98*********7")
    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Hai Good Morning");
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent);
} else {
    Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
    Uri uri = Uri.parse("market://details?id=com.whatsapp");
    Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(goToMarket);

}

private boolean whatsappInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}
Partharaj Deb
  • 864
  • 1
  • 8
  • 22
Satheesh
  • 723
  • 7
  • 18
  • 12
    Activity Not Fount exeption even when whatsapp installed – itzhar Jul 22 '15 at 18:55
  • 2
    No Activity found to handle Intent { act=android.intent.action.SENDTO typ=text/plain pkg=com.whatsapp (has extras) } – Rajesh Jul 12 '16 at 09:21
  • 2
    You need to remove this line to work with you sendIntent.setType("text/plain"); – MSaudi Apr 02 '17 at 17:54
  • 3
    removing sendIntent.setType("text/plain") takes care of the Activity Not Found exeption not being thrown, but now the text is not added as message – Rik van Velzen Oct 16 '17 at 10:25
  • looks like it's not possible anymore, the activity that receives the intent has some reference to "sms_body" but I'm unable to make it work – sherpya Dec 08 '19 at 00:03
11

Tested on Marshmallow S5 and it works!

    Uri uri = Uri.parse("smsto:" + "phone number with country code");
    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent); 

This will open a direct chat with a person, if whatsapp not installed this will throw exception, if phone number not known to whatsapp they will offer to send invite via sms or simple sms message

Rainb
  • 1,965
  • 11
  • 32
Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
8

Here is the latest way to send a message via Whatsapp, even if the receiver's phone number is not in your Whatsapp chat or phone's Contacts list.

private fun openWhatsApp(number: String) {
    try {
        packageManager.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES)
        val intent = Intent(
            Intent.ACTION_VIEW,
            Uri.parse("https://wa.me/$number?text=I'm%20interested%20in%20your%20car%20for%20sale")
        )
        intent.setPackage("com.whatsapp")
        startActivity(intent)
    } catch (e: PackageManager.NameNotFoundException) {
        Toast.makeText(
            this,
            "Whatsapp app not installed in your phone",
            Toast.LENGTH_SHORT
        ).show()
        e.printStackTrace()
    }
}

intent.setPackage("com.whatsapp") will help you to avoid Open With chooser and open Whatsapp directly.

Importent Note: If You are ending in catch statement, even if Whatsapp is installed. Please add queries to manifest.xml as follows:

<queries>
   <package android:name="com.whatsapp" />
</queries>

Please see this answer for more details.

Chintan Bawa
  • 1,376
  • 11
  • 15
  • Thanks for this helpful answer. What is the purpose of the getPackageInfo() call? I ask because the result don't seem to be used. Is it to trigger the NameNotFoundException? – LarsH Oct 14 '22 at 14:56
  • 1
    You get it right @LarsH. getPackageInfo() call is to ensure if Whatsapp is installed in the the phone or not. – Chintan Bawa Oct 14 '22 at 19:42
7

use this singleline code use to Sending message through WhatsApp

//NOTE : please use with country code first 2digits without plus signed
try {
      String mobile = "911234567890";
      String msg = "Its Working";
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=" + mobile + "&text=" + msg)));
      }catch (Exception e){
        //whatsapp app not install
     }
milan pithadia
  • 840
  • 11
  • 16
4

To check if WhatsApp is installed in device and initiate "click to chat" in WhatsApp:

Kotlin:

try {
    // Check if whatsapp is installed
    context?.packageManager?.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA)
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/$internationalPhoneNumber"))
    startActivity(intent)
} catch (e: NameNotFoundException) {
    Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}

Java:

try {
    // Check if whatsapp is installed
    getPackageManager().getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
    Intent intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/" + internationalPhoneNumber));
    startActivity(intent);
} catch (NameNotFoundException e) {
    Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
}

getPackageInfo() throws NameNotFoundException if WhatsApp is not installed.

The internationalPhoneNumber variable is used to access the phone number.

Reference:

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
3

The following code is used by Google Now App and will NOT work for any other application.

I'm writing this post because it makes me angry, that WhatsApp does not allow any other developers to send messages directly except for Google.

And I want other freelance-developers to know, that this kind of cooperation is going on, while Google keeps talking about "open for anybody" and WhatsApp says they don't want to provide any access to developers.

Recently WhatsApp has added an Intent specially for Google Now, which should look like following:

Intent intent = new Intent("com.google.android.voicesearch.SEND_MESSAGE_TO_CONTACTS");
intent.setPackage("com.whatsapp");
intent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.VoiceMessagingActivity"));

intent.putExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_CHAT_ID", number);
intent.putExtra("android.intent.extra.TEXT", text);
intent.putExtra("search_action_token", ?????);

I could also find out that "search_action_token" is a PendingIntent that contains an IBinder-Object, which is sent back to Google App and checked, if it was created by Google Now.

Otherwise WhatsApp will not accept the message.

black-hawk
  • 151
  • 1
  • 5
  • Interesting! but can you explain more about "search_action_token" how can we get and implement it. – Bilal Mustafa Mar 05 '18 at 21:40
  • APK com.google.android.googlequicksearchbox Class com.google.android.search.verification.api.SearchActionVerificationService Method createGoogleVerificationIntent – black-hawk Mar 07 '18 at 10:05
3

Currently, the only official API that you may make a GET request to:

https://api.whatsapp.com/send?phone=919773207706&text=Hello

Anyways, there is a secret API program already being ran by WhatsApp

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/19741411) – Kumar Saurabh May 16 '18 at 07:35
  • 1
    @KumarSaurabh This is not a link, it's a GET request – Zameer Ansari May 16 '18 at 10:03
3

As the documentation says you can just use an URL like:

https://wa.me/15551234567

Where the last segment is the number in in E164 Format

Uri uri = Uri.parse("https://wa.me/15551234567");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
GVillani82
  • 17,196
  • 30
  • 105
  • 172
3

This is what worked for me :

        Uri uri = Uri.parse("https://api.whatsapp.com/send?phone=" + "<number>" + "&text=" + "Hello WhatsApp!!");
        Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(sendIntent);
mchouhan_google
  • 1,775
  • 1
  • 20
  • 28
2

This works to me:

PackageManager pm = context.getPackageManager();
try {
    pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
    Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName,
                    ri.activityInfo.name));
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, element);

} catch (NameNotFoundException e) {
    ToastHelper.MakeShortText("Whatsapp have not been installed.");
}
Cabezas
  • 9,329
  • 7
  • 67
  • 69
2

Use direct URL of whatsapp

String url = "https://api.whatsapp.com/send?phone="+number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
2

You'll want to use a URL in the following format...

https://api.whatsapp.com/send?text=text

Then you can have it send whatever text you'd like. You also have the option to specify a phone number...

https://api.whatsapp.com/send?text=text&phone=1234

What you CANNOT DO is use the following:

https://wa.me/send?text=text

You will get...

We couldn't find the page you were looking for

wa.me, though, will work if you supply both a phone number and text. But, for the most part, if you're trying to make a sharing link, you really don't want to indicate the phone number, because you want the user to select someone. In that event, if you don't supply the number and use wa.me as URL, all of your sharing links will fail. Please use app.whatsapp.com.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
1

Check this code,

    public void share(String subject,String text) {
     final Intent intent = new Intent(Intent.ACTION_SEND);

String score=1000;
     intent.setType("text/plain");
     intent.putExtra(Intent.EXTRA_SUBJECT, score);
     intent.putExtra(Intent.EXTRA_TEXT, text);

     startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
Basim Sherif
  • 5,384
  • 7
  • 48
  • 90
1

this is much lengthy but surly working. enjoy your code:)

 //method used to show IMs
private void show_custom_chooser(String value) {
    List<ResolveInfo> list = null;
    final Intent email = new Intent(Intent.ACTION_SEND);
    email.setData(Uri.parse("sms:"));
    email.putExtra(Intent.EXTRA_TEXT, "" + value);
    email.setType("text/plain"); // vnd.android-dir/mms-sms

    WindowManager.LayoutParams WMLP = dialogCustomChooser.getWindow()
            .getAttributes();
    WMLP.gravity = Gravity.CENTER;
    dialogCustomChooser.getWindow().setAttributes(WMLP);
    dialogCustomChooser.getWindow().setBackgroundDrawable(
            new ColorDrawable(android.graphics.Color.TRANSPARENT));
    dialogCustomChooser.setCanceledOnTouchOutside(true);
    dialogCustomChooser.setContentView(R.layout.about_dialog);
    dialogCustomChooser.setCancelable(true);
    ListView lvOfIms = (ListView) dialogCustomChooser
            .findViewById(R.id.listView1);
    PackageManager pm = getPackageManager();
    List<ResolveInfo> launchables = pm.queryIntentActivities(email, 0);
    // ////////////new
    list = new ArrayList<ResolveInfo>();
    for (int i = 0; i < launchables.size(); i++) {
        String string = launchables.get(i).toString();
        Log.d("heh", string);
//check only messangers
        if (string.contains("whatsapp")) {
            list.add(launchables.get(i));
        }
    }
    Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
    int size = launchables.size();
    adapter = new AppAdapter(pm, list, MainActivity.this);
    lvOfIms.setAdapter(adapter);
    lvOfIms.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            ResolveInfo launchable = adapter.getItem(position);
            ActivityInfo activity = launchable.activityInfo;
            ComponentName name = new ComponentName(
                    activity.applicationInfo.packageName, activity.name);
            email.addCategory(Intent.CATEGORY_LAUNCHER);
            email.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            email.setComponent(name);
            startActivity(email);
            dialogCustomChooser.dismiss();
        }
    });
    dialogCustomChooser.show();

}
John smith
  • 1,781
  • 17
  • 27
1

I'm really late here but I believe that nowadays we have shorter and better solutions to send messages through WhatsApp.

You can use the following to call the system picker, then choose which app you will use to share whatever you want.

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);

If you are really need to send through WhatsApp all you need to do is the following (You will skip the system picker)

 Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.setType("text/plain");
    // Put this line here
    sendIntent.setPackage("com.whatsapp");
    //
    startActivity(sendIntent);

If you need more information you can find it here: WhatsApp FAQ

Amit Basliyal
  • 840
  • 1
  • 10
  • 28
Will
  • 804
  • 2
  • 8
  • 17
1
private fun sendWhatsappMessage(phoneNumber:String, text:String) {        
  val url = if (Intent().setPackage("com.whatsapp").resolveActivity(packageManager) != null) {
        "whatsapp://send?text=Hello&phone=$phoneNumber"
    } else {
        "https://api.whatsapp.com/send?phone=$phoneNumber&text=$text"
    }

    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    startActivity(browserIntent)
}

This is a much easier way to achieve this. This code checks if whatsapp is installed on the device. If it is installed, it bypasses the system picker and goes to the contact on whatsapp and prefields the text in the chat. If not installed it opens whatsapp link on your web browser.

Adekola Akano
  • 169
  • 2
  • 7
1

Sending to WhatsApp Number that exist in your contact list. Notice that we are using ACTION_SEND

 Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
 whatsappIntent.setType("text/plain");
 whatsappIntent.setPackage("com.whatsapp");
 whatsappIntent.putExtra(Intent.EXTRA_TEXT, "SMS TEXT, TEXT THAT YOU NEED TO SEND");
 try {
   startActivityForResult(whatsappIntent, 100);
 } catch (Exception e) {
   Toast.makeText(YourActivity.this, "App is not installed", Toast.LENGTH_SHORT).show();
 }

If Number doesn't exist in contact list. Use WhatsApp API.

 String number = number_phone.getText().toString(); // I toke it from Dialog box
 number = number.substring(1); // To remove 0 at the begging of number (Optional) but needed in my case
 number = "962" + number; // Replace it with your country code
 String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + Uri.parse("Text that you want to send to the current user");
 Intent whatsappIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
 whatsappIntent.setPackage("com.whatsapp");
 whatsappIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 try {
   context.startActivity(whatsappIntent);
 } catch (android.content.ActivityNotFoundException ex) {
   Toast.makeText(YourActivity.this, "App is not installed", Toast.LENGTH_SHORT).show();
 }
WardNsour
  • 313
  • 1
  • 2
  • 16
0

This works to me:

public static void shareWhatsApp(Activity appActivity, String texto) {

    Intent sendIntent = new Intent(Intent.ACTION_SEND);     
    sendIntent.setType("text/plain");
    sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, texto);

    PackageManager pm = appActivity.getApplicationContext().getPackageManager();
    final List<ResolveInfo> matches = pm.queryIntentActivities(sendIntent, 0);
    boolean temWhatsApp = false;
    for (final ResolveInfo info : matches) {
      if (info.activityInfo.packageName.startsWith("com.whatsapp"))  {
          final ComponentName name = new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name);
          sendIntent.addCategory(Intent.CATEGORY_LAUNCHER);
          sendIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_TASK);
          sendIntent.setComponent(name);
          temWhatsApp = true;
          break;
      }
    }               

    if(temWhatsApp) {
        //abre whatsapp
        appActivity.startActivity(sendIntent);
    } else {
        //alerta - você deve ter o whatsapp instalado
        Toast.makeText(appActivity, appActivity.getString(R.string.share_whatsapp), Toast.LENGTH_SHORT).show();
    }
}
0

get the contact number whom you want to send the message and create uri for whatsapp, here c is a Cursor returning the selected contact.

Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
i.setType("text/plain");
i.setPackage("com.whatsapp");           // so that only Whatsapp reacts and not the chooser
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "I'm the body.");
startActivity(i);
Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
0

From the documentation

To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.

Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

Code example

val phoneNumber = "13492838472"
    val text = "Hey, you know... I love StackOverflow :)"
    val uri = Uri.parse("https://wa.me/$phoneNumber/?text=$text")
    val sendIntent = Intent(Intent.ACTION_VIEW, uri)
    startActivity(sendIntent)
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
0

This one worked finally for me in Kotlin:

private fun navigateToWhatsApp() {
        try {
            val url = "https://api.whatsapp.com/send?phone=+91${getString(R.string.contact)}"
            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).setPackage("com.whatsapp"))
        } catch (e: Exception) {
            showToast("Whatsapp app not installed in your device")
        }
    }
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
-1

The following API can be used in c++ as shown in my article.

You need to define several constants:

//
#define    GroupAdmin                <YOUR GROUP ADMIN MOBILE PHONE>
#define GroupName                <YOUR GROUP NAME>
#define CLIENT_ID                <YOUR CLIENT ID>
#define CLIENT_SECRET            <YOUR CLIENT SECRET>

#define GROUP_API_SERVER        L"api.whatsmate.net"
#define GROUP_API_PATH          L"/v3/whatsapp/group/text/message/12"
#define IMAGE_SINGLE_API_URL    L"http://api.whatsmate.net/v3/whatsapp/group/image/message/12"

//

Then you connect to the API’s endpoint.

hOpenHandle = InternetOpen(_T("HTTP"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hOpenHandle == NULL)
{
    return false;
}

hConnectHandle = InternetConnect(hOpenHandle,
    GROUP_API_SERVER,
    INTERNET_DEFAULT_HTTP_PORT,
    NULL, NULL, INTERNET_SERVICE_HTTP,
    0, 1);

if (hConnectHandle == NULL)
{
    InternetCloseHandle(hOpenHandle);
    return false;
}

Then send both header and body and wait for the result that needs to be “OK”.

Step 1 - open an HTTP request:

const wchar_t *AcceptTypes[] = { _T("application/json"),NULL };
HINTERNET hRequest = HttpOpenRequest(hConnectHandle, _T("POST"), GROUP_API_PATH, NULL, NULL, AcceptTypes, 0, 0);

if (hRequest == NULL)
{
    InternetCloseHandle(hConnectHandle);
    InternetCloseHandle(hOpenHandle);
    return false;
}

Step 2 - send the header:

std::wstring HeaderData;

HeaderData += _T("X-WM-CLIENT-ID: ");
HeaderData += _T(CLIENT_ID);
HeaderData += _T("\r\nX-WM-CLIENT-SECRET: ");
HeaderData += _T(CLIENT_SECRET);
HeaderData += _T("\r\n");
HttpAddRequestHeaders(hRequest, HeaderData.c_str(), HeaderData.size(), NULL);

Step 3 - send the message:

std::wstring WJsonData;
WJsonData += _T("{");
WJsonData += _T("\"group_admin\":\"");
WJsonData += groupAdmin;
WJsonData += _T("\",");
WJsonData += _T("\"group_name\":\"");
WJsonData += groupName;
WJsonData += _T("\",");
WJsonData += _T("\"message\":\"");
WJsonData += message;
WJsonData += _T("\"");
WJsonData += _T("}");

const std::string JsonData(WJsonData.begin(), WJsonData.end());

bResults = HttpSendRequest(hRequest, NULL, 0, (LPVOID)(JsonData.c_str()), JsonData.size());

Now just check the result:

TCHAR StatusText[BUFFER_LENGTH] = { 0 };
DWORD StatusTextLen = BUFFER_LENGTH;
HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_TEXT, &StatusText, &StatusTextLen, NULL);
bResults = (StatusTextLen && wcscmp(StatusText, L"OK")==FALSE);
Michael Haephrati
  • 3,660
  • 1
  • 33
  • 56