Blog / October 23, 2020 / 2 mins read / By Suneet Agrawal

Android : Share message directly to whatsapp contact

Whatsapp is something which doesn’t require any introduction. It’s a conversation app used by millions of users across the world. These million users make it unique for developers also to give special attention when it comes to sharing some message through Whatsapp.

During recent times, I was asked multiple times in the comments section or even emails, if there is any possible way where we can send the text message directly to a WhatsApp contact?

The ideal way any app accepts text, image, video or any other format for sharing is through intent filters defined in the manifest file.

Whatsapp also does the same and accepts all possible format (with some size and other limitations) but that will take you to a contact selection screen in Whatsapp.

If you want to share the text directly to a contact on WhatsApp, there is a hack which is actually not documented anywhere but using the same we can achieve it.

There is an API from WhatsApp which accepts ‘phone’ and ’text’ and query parameters and if you call that API, it actually opens WhatsApp, check if that number exists on WhatsApp, if yes it opens conversation with that number and paste the message. If the contact or mobile numbers doesn’t exist on WhatsApp, it shows a popup saying contact doesn’t exist on WhatsApp.

fun onWhatsAppShareClicked(context: Context, mobileNumber: String) {
    val url =
        "https://api.whatsapp.com/send?phone=${mobileNumber}&text=You%20can%20now%20send%20me%20audio%20and%20video%20messages%20on%20the%20app%20-%20Chirp.%20%0A%0Ahttps%3A//bit.ly/chirp_android"
        
    val intent = Intent(Intent.ACTION_VIEW).apply {
        this.data = Uri.parse(url)
        this.`package` = "com.whatsapp"
    }

    try {
        context.startActivity(intent)
    } catch (ex : ActivityNotFoundException){
        //whatsapp not installled
    }
}

Things to notice here

  1. We are not triggering the share intent. Instead, we are triggering an Action_VIEW intent with a URI which holds our url to hit.
  2. We are setting the package name exclusively to WhatsApp package in the intent.
  3. Before triggering this you need to check whether Whatsapp is installed or not using below code.
fun isPackageInstalled(context: Context, packageName: String): Boolean {
        return try {
            context.packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
            true
        } catch (ex: Exception) {
            false
        }
    }

Limitations

  • We can only share text in this format. we can’t pass an image, video or any other format in this way. But we can pass an URL to an image which can be on the server.

Complete code

Comments