How to send message on WhatsApp in Android using Kotlin

07 Aug, 2020
Whatsapp is the one of most popular messaging App. Many android applications need the functionality to share some messages directly from their app to WhatsApp. For example, if a user wants to share the app or share a message from the app then this functionality comes in use. Either user can send a text or a predefined text can also be sent through this. This article demonstrates how an android application can send messages on WhatsApp. Whatsapp must be installed on the user’s device.
In this article, we will try to create an android app that sends message on WhatsApp using Kotlin.
Note: To view how to do this in Java, please refer How to send message on WhatsApp in Android using Java.
Approach
Step 1: Modify activity_main.xml fileOpen the activity_main.xml file and add the layout code. activity_main.xml contains a Linear Layout which contains a EditText to input the message and a Button to submit the message.
activity_main.xml
<LinearLayout       xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      tools:context=".MainActivity"      android:orientation="vertical">    <!--EditText to take message input from user-->  <EditText      android:id="@+id/message"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:layout_margin="16dp"      android:hint="Enter you message here"      android:lines="8"      android:inputType="textMultiLine"      android:gravity="left|top"      />    <!--Button to send message on Whatsapp-->  <Button      android:id="@+id/submit"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_gravity="center_horizontal"      android:text="Submit"      android:background="@color/colorPrimary"      android:textColor="@android:color/white"/></LinearLayout>
Step 2: Working with MainActivity.kt file
Take the reference of EditText and Button in Kotlin file. References are taken using the ids with the help of findViewById() method.Taking reference of EditText// Referencing the Edit Textval messageEditText = findViewById<EditText>(R.id.message)Similarly taking reference of button// Referencing the buttonval submit = findViewById<Button>(R.id.submit)
Taking reference of EditText
// Referencing the Edit Textval messageEditText = findViewById<EditText>(R.id.message)
Similarly taking reference of button
// Referencing the buttonval submit = findViewById<Button>(R.id.submit)
Write a function to send message to WhatsApp. Create an intent with ACTION_SEND and specify the whatsapp package name to this so that it opens directly. com.whatsapp is the package name for official WhatsApp application.fun sendMessage(message:String){           // Creating intent with action send         val intent = Intent(Intent.ACTION_SEND)           // Setting Intent type         intent.type = "text/plain"           // Setting whatsapp package name         intent.setPackage("com.whatsapp")           // Give your message here         intent.putExtra(Intent.EXTRA_TEXT, message)           // Checking whether whatsapp is installed or not         if (intent.resolveActivity(packageManager) == null) {             Toast.makeText(this,                             "Please install whatsapp first.",                             Toast.LENGTH_SHORT).show()             return         }           // Starting Whatsapp         startActivity(intent)     }
fun sendMessage(message:String){           // Creating intent with action send         val intent = Intent(Intent.ACTION_SEND)           // Setting Intent type         intent.type = "text/plain"           // Setting whatsapp package name         intent.setPackage("com.whatsapp")           // Give your message here         intent.putExtra(Intent.EXTRA_TEXT, message)           // Checking whether whatsapp is installed or not         if (intent.resolveActivity(packageManager) == null) {             Toast.makeText(this,                             "Please install whatsapp first.",                             Toast.LENGTH_SHORT).show()             return         }           // Starting Whatsapp         startActivity(intent)     }
Set the click listener using setOnClickListener on the button to send the message. Get the text entered by the user and call the function to send message on whatsapp.// Setting on click listenersubmit.setOnClickListener {    val message = messageEditText.text.toString() // Calling the function    sendMessage(message);}
// Setting on click listenersubmit.setOnClickListener {    val message = messageEditText.text.toString() // Calling the function    sendMessage(message);}
Below is the complete MainActivity.kt file
MainActivity.kt
package com.gfg  import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast  class MainActivity : AppCompatActivity() {      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // Referencing the Edit Text        val messageEditText = findViewById<EditText>(R.id.message)          // Referencing the button        val submit = findViewById<Button>(R.id.submit)          // Setting on click listener        submit.setOnClickListener {            val message = messageEditText.text.toString()          // Calling the function        sendMessage(message);        }    }      fun sendMessage(message: String) {          // Creating intent with action send        val intent = Intent(Intent.ACTION_SEND)          // Setting Intent type        intent.type = "text/plain"          // Setting whatsapp package name        intent.setPackage("com.whatsapp")          // Give your message here        intent.putExtra(Intent.EXTRA_TEXT, message)          // Checking whether whatsapp is installed or not        if (intent.resolveActivity(packageManager) == null) {            Toast.makeText(this,                            "Please install whatsapp first.",                            Toast.LENGTH_SHORT).show()            return        }          // Starting Whatsapp        startActivity(intent)    }}
Output
android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Content Providers in Android with Example
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Kotlin Higher-Order Functions