[android] Send text to specific contact programmatically (whatsapp)

I wanted to know how I can send text to a specific whatsapp contact. I found some code to view a specific contact, but not to send data.

Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
    new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
    new String[] { id }, null);
c.moveToFirst();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));

startActivity(i);
c.close();

This works fine for viewing a whatsapp-contact, but how can I add some text now? Or didn't the Whatsapp-developer implement such kind of an api?

This question is related to android android-intent contact whatsapp

The answer is


Whatsapp and most other apps that integrate into the Android core components (like Contacts) use a mime-type based intent to launch a certain Activity within the application. Whatsapp uses 3 separate mimetypes - text messages (vnd.android.cursor.item/vnd.com.whatsapp.profile), voip calls (vnd.android.cursor.item/vnd.com.whatsapp.voip.call) and video calls(vnd.android.cursor.item/vnd.com.whatsapp.video.call). For each of these mimetypes, a separate activity is mapped inside the Manifest of the application. For ex: the mimetype (...whatsapp.profile) maps to an Activity (com.whatsapp.Conversation). You can see these in detail if you dump out all the Data rows that maps to any Whatsapp Raw_Contact in your Contacts database.

This is also how the Android Contacts app shows 3 separate rows of user action inside a "Whatsapp contact", and clicking either of these rows launches a separate function inside Whatsapp.

To launch a Conversation (chat) Activity for a certain contact in Whatsapp, you need to fire an intent containing MIME_TYPE and DATA_URL. The mimetype points to the mimetype corresponding to your action as defined inside Whatsapp's Raw Contact in Contacts database. The DATA_URL is the URI of the Raw_Contact in the Android contacts database.

String whatsAppMimeType = Uri.parse("vnd.android.cursor.item").buildUpon()
                                    .appendEncodedPath("vnd.com.whatsapp.profile").build().toString();

Uri uri = ContactsContract.RawContacts.CONTENT_URI.buildUpon()
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.whatsapp")
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "WhatsApp")
        .build();

Cursor cursor = getContentResolver().query(uri, null, null, null);
if (cursor==null || cursor.getCount()==0) continue;

cursor.moveToNext();
int rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
cursor.close();

// now search for the Data row entry that matches the mimetype and also points to this RawContact
Cursor dataCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        null,
        ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.Data.RAW_CONTACT_ID + "=?",
        new String[]{whatsAppMimeType, String.valueOf(rawContactId)}, null);
if (dataCursor==null || dataCursor.getCount()==0) continue;

dataCursor.moveToNext();
int dataRowId = dataCursor.getInt(dataCursor.getColumnIndex(ContactsContract.Data._ID));

Uri userRowUri = ContactsContract.Data.CONTENT_URI.buildUpon()
                        .appendPath(String.valueOf(dataRowId)).build();


// launch the whatsapp user chat activity
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(userRowUri, whatsAppMimeType);
startActivity(intent);

dataCursor.close();

This is the same way that all Contacts app use to launch a chat Activity for a Whatsapp contact. Inside this Activity, the application (Whatsapp) reads in the .getData() to get the DATA_URI which was passed to this Activity. The Android Contacts app uses a standard mechanism to use the URI of the Raw Contact in Whatsapp. Unfortunately, I am not aware of a way by which the .Conversation ativity in Whatsapp reads in any text / data information from the caller of the intent. This basically means that its possible (using a very standard technique) to launch a certain "user action" inside Whatsapp. Or for that matter, any similar app.


I've found the right way to do this:

Source code: phone and message are both String.

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

    try {
        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 yourself!


Check this answer. Here your number start with "91**********".

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_SEND);

sendIntent.setType("text/plain");                    
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");                   sendIntent.putExtra("jid",PhoneNumberUtils.stripSeparators("91**********")                   + "@s.whatsapp.net");                    
sendIntent.setPackage("com.whatsapp");                    
startActivity(sendIntent);

Whatsapp have its own API

    Intent sendIntent = new Intent("android.intent.action.MAIN");
                        sendIntent.setAction(Intent.ACTION_VIEW);
                        sendIntent.setPackage("com.whatsapp");
                        String url = "https://api.whatsapp.com/send?phone=" + "Phone with international format" + "&text=" + "your message";
                        sendIntent.setData(Uri.parse(url));
                        if(sendIntent.resolveActivity(context.getPackageManager()) != null){
                             startActivity(sendIntent);
                        }

Code updated check added for Activity is available or not.

See this documentation


In Python, you can do it the same way we do it with mobile application

 web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)

This will prepopulate the text for given mobile number(Enter the phone_no as CountryCode and the number eg +918888888888) Then using pyautogui you can press enter onto whatsapp.web

Working code :

def sendwhatmsg(phone_no, message, time_hour, time_min):
     '''Sends whatsapp message to a particulal number at given time'''
     if time_hour == 0:
         time_hour = 24
     callsec = (time_hour*3600)+(time_min*60)

     curr = time.localtime()
     currhr = curr.tm_hour
     currmin = curr.tm_min
     currsec = curr.tm_sec

     currtotsec = (currhr*3600)+(currmin*60)+(currsec)
     lefttm = callsec-currtotsec

     if lefttm <= 0:
         lefttm = 86400+lefttm

     if lefttm < 60:
         raise Exception("Call time must be greater than one minute")

     else:
         sleeptm = lefttm-60
         time.sleep(sleeptm)
         web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)
         time.sleep(60)
         pg.press('enter')

I've taken this from this repository - Github repo


This is the shortest way

    String mPhoneNumber = "+972505555555";
    mPhoneNumber = mPhoneNumber.replaceAll("+", "").replaceAll(" ", "").replaceAll("-","");
    String mMessage = "Hello world";
    String mSendToWhatsApp = "https://wa.me/" + mPhoneNumber + "?text="+mMessage;
    startActivity(new Intent(Intent.ACTION_VIEW,
            Uri.parse(
                    mSendToWhatsApp
            )));

See also the documentation of WhatsApp


Update 2020

     String number="+91 7*********";
            String url="https://api.whatsapp.com/send?phone="+number + "&text=" + "Your text here";
            Intent i=new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);

Send a text to specific contact programmatically (Whatsapp)

try {
    val i = Intent(Intent.ACTION_VIEW)
    val url = "https://api.whatsapp.com/send?phone=91XXXXXXXXXX&text=yourmessage"
    i.setPackage("com.whatsapp")
    i.data = Uri.parse(url)
    startActivity(i)
} catch (e: Exception) {
   e.printStackTrace()
   val uri = Uri.parse("market://details?id=com.whatsapp")
   val goToMarket = Intent(Intent.ACTION_VIEW, uri)
   startActivity(goToMarket)
}

private void sendToContactUs() {
     String phoneNo="+918000874386";

    Intent sendIntent = new Intent("android.intent.action.MAIN");
    sendIntent.setAction(Intent.ACTION_VIEW);
    sendIntent.setPackage("com.whatsapp");
    String url = "https://api.whatsapp.com/send?phone=" + phoneNo + "&text=" + "Unique Code - "+CommonUtils.getMacAddress();
    sendIntent.setDataAndType(Uri.parse(url),"text/plain");


    if(sendIntent.resolveActivity(getPackageManager()) != null){
        startActivity(sendIntent);
    }else{
        Toast.makeText(getApplicationContext(),"Please Install Whatsapp Massnger App in your Devices",Toast.LENGTH_LONG).show();
    }
}

This code is implemented with Kotlin.

I have 2 versions:

1) For known contacts

private fun openWhatsApp(dato: WhatsApp) {
    val isAppInstalled = appInstalledOrNot("com.whatsapp")
    if (isAppInstalled) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=${dato.whatsapp}"))
        startActivity(intent)
    } else {
        // WhatsApp not installed show toast or dialog
    }
}

private fun appInstalledOrNot(uri: String): Boolean {
    val pm = requireActivity().packageManager
    return try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}

In the case of being an unknown contact WhatsApp shows the following message

enter image description here

2) For unknown contacts

private fun openWhatsApp(dato: WhatsApp) {
    val isAppInstalled = appInstalledOrNot("com.whatsapp")
    if (isAppInstalled) {
        val sendIntent = Intent("android.intent.action.MAIN")
        sendIntent.setType("text/plain")
        sendIntent.setComponent(ComponentName("com.whatsapp", "com.whatsapp.Conversation"))
        sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(dato.whatsapp) + "@s.whatsapp.net")
        startActivity(sendIntent)
    } else {
        // WhatsApp not installed show toast or dialog
    }
}

private fun appInstalledOrNot(uri: String): Boolean {
    val pm = requireActivity().packageManager
    return try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}

Here am trying to send a text message in WhatsApp with another application.

Assume that we have a button, on button click ur calling below method.

sendTextMsgOnWhatsApp("+91 9876543210", "Hello, this my test message");

public void sendTextMsgOnWhatsApp(String sContactNo, String sMessage) {
        String toNumber = sContactNo; // contains spaces, i.e., example +91 98765 43210
        toNumber = toNumber.replace("+", "").replace(" ", "");

        /*this method contactIdByPhoneNumber() will get unique id for given contact,
        if this return's null then it means that you don't have any contact save with this mobile no.*/
        String sContactId = contactIdByPhoneNumber(toNumber);

        if (sContactId != null && sContactId.length() > 0) {

            /*
             * Once We get the contact id, we check whether contact has a registered with WhatsApp or not.
             * this hasWhatsApp(hasWhatsApp) method will return null,
             * if contact doesn't associate with whatsApp services.
             * */
            String sWhatsAppNo = hasWhatsApp(sContactId);

            if (sWhatsAppNo != null && sWhatsAppNo.length() > 0) {
                Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
                sendIntent.putExtra(Intent.EXTRA_TEXT, sMessage);
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setPackage("com.whatsapp");
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            } else {
                // this contact does not exist in any WhatsApp application
                Toast.makeText(this, "Contact not found in WhatsApp !!", Toast.LENGTH_SHORT).show();
            }
        } else {
            // this contact does not exist in your contact
            Toast.makeText(this, "create contact for " + toNumber, Toast.LENGTH_SHORT).show();
        }
    }

    private String contactIdByPhoneNumber(String phoneNumber) {
        String contactId = null;
        if (phoneNumber != null && phoneNumber.length() > 0) {
            ContentResolver contentResolver = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            String[] projection = new String[]{ContactsContract.PhoneLookup._ID};

            Cursor cursor = contentResolver.query(uri, projection, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
                }
                cursor.close();
            }
        }
        return contactId;
    }

    public String hasWhatsApp(String contactID) {
        String rowContactId = null;
        boolean hasWhatsApp;

        String[] projection = new String[]{ContactsContract.RawContacts._ID};
        String selection = ContactsContract.RawContacts.CONTACT_ID + " = ? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " = ?";
        String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
        Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
        if (cursor != null) {
            hasWhatsApp = cursor.moveToNext();
            if (hasWhatsApp) {
                rowContactId = cursor.getString(0);
            }
            cursor.close();
        }
        return rowContactId;
    }

Add this below permission in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />

you can also select WhatsApp business vs WhatsApp

String url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" + 
  URLEncoder.encode(messageText, "UTF-8");
  if(useWhatsAppBusiness){
    intent.setPackage("com.whatsapp.w4b");
  } else {
    intent.setPackage("com.whatsapp");
  }
  URLEncoder.encode(messageText, "UTF-8");
  intent.setData(Uri.parse(url));

  if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent);
  } else {
    Toast.makeText(this, "WhatsApp application not found", Toast.LENGTH_SHORT).show();
  }

Check out my answer : https://stackoverflow.com/a/40285262/5879376

 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");//phone number without "+" prefix

 startActivity(sendIntent);

This will first search for the specified contact and then open a chat window.

Note: phone_number and str are variables.

Uri mUri = Uri.parse("https://api.whatsapp.com/send?
phone=" + phone_no + "&text=" + str);
Intent mIntent = new Intent("android.intent.action.VIEW", mUri);
mIntent.setPackage("com.whatsapp");
startActivity(mIntent);

Use this function. Don't forget to save the WhatsApp Number on your mobile before sending trigger the function.

private void openWhatsApp() {
        Uri uri = Uri.parse("smsto:"+ "12345");
        Intent i = new Intent(Intent.ACTION_SENDTO,uri);
        i.setPackage("com.whatsapp");
        startActivity(i);
    }

_x000D_
_x000D_
 public void shareWhatsup(String text) {_x000D_
_x000D_
_x000D_
        String smsNumber = "91+" + "9879098469"; // E164 format without '+' sign_x000D_
_x000D_
        Intent intent = new Intent(Intent.ACTION_VIEW);_x000D_
_x000D_
        try {_x000D_
            String url = "https://api.whatsapp.com/send?phone=" + smsNumber + "&text=" + URLEncoder.encode(text, "UTF-8");_x000D_
            intent.setPackage("com.whatsapp");_x000D_
            intent.setData(Uri.parse(url));_x000D_
        } catch (Exception e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
_x000D_
        //    intent.setAction(Intent.ACTION_SEND);_x000D_
        //   intent.setType("image/jpeg");_x000D_
        //   intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUriArray);_x000D_
        startActivity(intent);_x000D_
_x000D_
_x000D_
    }
_x000D_
_x000D_
_x000D_


Here is a way how to send message in WhatsApp in KOTLIN

    private fun sendMessage(phone: String, message: String) {
        val pm = requireActivity().packageManager
        val i = Intent(Intent.ACTION_VIEW)
        try {
            val url = "https://api.whatsapp.com/send?phone=$phone&text=" + URLEncoder.encode(
                message,
                "UTF-8"
            )
            i.setPackage("com.whatsapp")
            i.data = Uri.parse(url)
            if (i.resolveActivity(pm) != null) {
                context?.startActivity(i)
            }
        } catch (e: PackageManager.NameNotFoundException) {
            Toast.makeText(requireContext(), "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
        }
    }

Bitmap bmp = null;
            bmp = ((BitmapDrawable) tmpimg.getDrawable()).getBitmap();
            Uri bmpUri = null;
            try {
                File file = new File(getBaseContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".jpg");
                FileOutputStream out = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.close();
                bmpUri = Uri.fromFile(file);

            } catch (IOException e) {
                e.printStackTrace();
            }

            String toNumber = "+919999999999"; 
            toNumber = toNumber.replace("+", "").replace(" ", "");
            Intent shareIntent =new Intent("android.intent.action.MAIN");
            shareIntent.setAction(Intent.ACTION_SEND);
            String ExtraText;
            ExtraText =  "Share Text";
            shareIntent.putExtra(Intent.EXTRA_TEXT, ExtraText);
            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            shareIntent.setType("image/jpg");
            shareIntent.setPackage("com.whatsapp");
            shareIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {

                startActivity(shareIntent);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(getBaseContext(), "Sharing tools have not been installed.", Toast.LENGTH_SHORT).show();
            }

        }

try this, worked for me ! . Just use intent

   Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(whatsappUrl()));
   startActivity(intent);

Build whatsapp url. add country code in whatsapp phone number https://countrycode.org/

public static String whatsappUrl(){

    final String BASE_URL = "https://api.whatsapp.com/";
    final String WHATSAPP_PHONE_NUMBER = "628123232323";    //'62' is country code for Indonesia
    final String PARAM_PHONE_NUMBER = "phone";
    final String PARAM_TEXT = "text";
    final String TEXT_VALUE = "Hello, How are you ?";

    String newUrl = BASE_URL + "send";

    Uri builtUri = Uri.parse(newUrl).buildUpon()
            .appendQueryParameter(PARAM_PHONE_NUMBER, WHATSAPP_PHONE_NUMBER)
            .appendQueryParameter(PARAM_TEXT, TEXT_VALUE)
            .build();

    return buildUrl(builtUri).toString();
}

public static URL buildUrl(Uri myUri){

    URL finalUrl = null;
    try {
        finalUrl = new URL(myUri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();

    }
    return finalUrl;
}

 private void openWhatsApp() {
       //without '+'
        try {
            Intent sendIntent = new Intent("android.intent.action.MAIN");

            //sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra("jid",whatsappId);
            sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            sendIntent.setPackage("com.whatsapp");
            startActivity(sendIntent);
        } catch(Exception e) {
            Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
            Log.e("Error",e+"")    ;    }
    }

try {
                    String text = "Hello, Admin sir";// Replace with your message.

                    String toNumber = "xxxxxxxxxxxx"; // Replace with mobile phone number without +Sign or leading zeros, but with country code
                    //Suppose your country is India and your phone number is “xxxxxxxxxx”, then you need to send “91xxxxxxxxxx”.


                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + toNumber + "&text=" + text));
                    context.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));

                }

This will first search for the specified contact and then open a chat window. And if WhatsApp is not installed then try-catch block handle this.

    String digits = "\\d+";
    String mob_num = "987654321";     
    if (mob_num.matches(digits)) 
            {
        try {
              //linking for whatsapp
              Uri uri = Uri.parse("whatsapp://send?phone=+91" + mob_num);
              Intent i = new Intent(Intent.ACTION_VIEW, uri);
              startActivity(i);
            }
            catch (ActivityNotFoundException e){
                    e.printStackTrace();
                    //if you're in anonymous class pass context like "YourActivity.this"
                    Toast.makeText(this, "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
            }
        }

I have done it!

private void openWhatsApp() {
    String smsNumber = "7****"; // E164 format without '+' sign
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
    sendIntent.setPackage("com.whatsapp");
    if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
        Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
        return;    
    }
    startActivity(sendIntent);
}

I think the answer is a mix of your question and this answer here: https://stackoverflow.com/a/15931345/734687 So I would try the following code:

  1. change ACTION_VIEW to ACTION_SENDTO
  2. set the Uri as you did
  3. set the package to whatsapp
Intent i = new Intent(Intent.ACTION_SENDTO, 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);

I looked into the Whatsapp manifest and saw that ACTION_SEND is registered to the activity ContactPicker, so that will not help you. However ACTION_SENDTO is registered to the activity com.whatsapp.Conversation which sounds more adequate for your problem.

Whatsapp can work as a replacement for sending SMS, so it should work like SMS. When you do not specify the desired application (via setPackage) Android displays the application picker. Thererfor you should just look at the code for sending SMS via intent and then provide the additional package information.

Uri uri = Uri.parse("smsto:" + smsNumber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra("sms_body", smsText);  
i.setPackage("com.whatsapp");  
startActivity(i);

First try just to replace the intent ACTION_SEND to ACTION_SENDTO . If this does not work than provide the additional extra sms_body. If this does not work than try to change the uri.

Update I tried to solve this myself and was not able to find a solution. Whatsapp is opening the chat history, but doesn't take the text and send it. It seems that this functionality is just not implemented.


It lets you open WhatsApp conversation screen for that specific user you are trying to communicate with:

private void openWhatsApp() {
    String smsNumber = "91XXXXXXXX20";
    boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
    if (isWhatsappInstalled) {

        Intent sendIntent = new Intent("android.intent.action.MAIN");
        sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
        sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber) + "@s.whatsapp.net");//phone number without "+" prefix

        startActivity(sendIntent);
    } else {
        Uri uri = Uri.parse("market://details?id=com.whatsapp");
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        Toast.makeText(this, "WhatsApp not Installed",
                Toast.LENGTH_SHORT).show();
        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;
}

This approach works with WhatsApp Business app as well!

Change package name as sendIntent.setPackage("com.whatsapp.w4b"); for WhatsApp Business.

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.

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!


Instead of biasing to share the content to whats app.

Following code is a generic code that will give a simple solution using "ShareCompact" that android opens the list of apps that supports the sharing the content.

Here I am sharing the data of mime-type text/plain.

    String mimeType = "text/plain"
    String Message  = "Hi How are you doing?"

    ShareCompact.IntentBuilder
                .from(this)
                .setType(mimeType)
                .setText(Message)
                .startChooser()

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-intent

Kotlin Android start new Activity Open Facebook Page in Facebook App (if installed) on Android Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23 Not an enclosing class error Android Studio Parcelable encountered IOException writing serializable object getactivity() Sending intent to BroadcastReceiver from adb How to pass ArrayList<CustomeObject> from one activity to another? Android Intent Cannot resolve constructor Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT Android - java.lang.SecurityException: Permission Denial: starting Intent

Examples related to contact

Send text to specific contact programmatically (whatsapp)

Examples related to whatsapp

Get Path from another app (WhatsApp) Does WhatsApp offer an open API? Web link to specific whatsapp contact Mobile website "WhatsApp" button to send message to a specific number Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work Sharing link on WhatsApp from mobile website (not application) for Android Add Whatsapp function to website, like sms, tel Provide an image for WhatsApp link sharing Send text to specific contact programmatically (whatsapp) WhatsApp API (java/python)