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.
Approach
Step 1:Open the activity_main.xml file and add the layout code. A message input container as EditText and a Button to send this message is added.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<xml0
xml1xml2=xml4
xml1xml6=xml8
xml1version0=version2
xml1version4=version6
xml1version8=version6
xml1=2==4
xml1=6==8=9
"1.0"0
"1.0"1"1.0"2
"1.0"1<"1.0"5
"1.0"6"1.0"7="1.0"9
"1.0"6version4=version6
"1.0"6version8=encoding7
"1.0"6encoding9==1
"1.0"6=3==5
"1.0"6=7==9
"1.0"6"utf-8"1="utf-8"3
"1.0"6"utf-8"5="utf-8"7
"1.0"6"utf-8"9
"1.0"0
"1.0"1?>2
"1.0"1<?>5
"1.0"6"1.0"7=?>9
"1.0"6version4=encoding7
"1.0"6version8=encoding7
"1.0"6<9=xml01
"1.0"6xml03=xml05
"1.0"6xml07=xml09
"1.0"6xml11=xml13"utf-8"9
"1.0"0
xml16xml0=9
Step 2: Take the reference of EditText and Button in Java file. References are taken using the ids with the help of findViewById() method.
- Taking reference to EditText
EditText messageEditText = findViewById(R.id.message);
- Taking reference to Button
Button submit = findViewById(R.id.submit);
Step 3: Write function to send message to whatsapp. Create an intent with ACTION_SEND and specify the whatsapp package name to this so that it opens whatsapp directly.
com.whatsapp is the package name for official whatsapp application.
xml19 xml20 xml21
xml22
"1.0"0
xml1xml25
xml1xml27
xml28=xml30 xml31
"1.0"0
xml1xml34xml35xml36
xml1xml38xml39xml36
"1.0"0
xml1xml43
xml1xml45
xml28xml47
xml28xml49
"1.0"0
xml1xml52
xml1xml54
xml1xml56 xml57
xml58xml59
xml60xml61
xml28xml63xml64xml65
xml28xml67
xml68xml69xml70
xml68xml72xml70
xml68xml75
xml58xml77
xml28xml79xml80
xml1xml82
"1.0"0
xml1xml85
xml1xml87
xml82
Step 4: Set onClickListener to the button. It takes the text entered by the user and calls the function sendMessage in which the text message is sent as a parameter.