0
votes

How can I Open a Whatsapp chat with a specific contact by clicking on a button in my app?

That's the code I use. It opens WhatsApp and let me search the contact I want to send the message to, but it doesn't open the WhatsApp chat with the specific contact number I gave it to.

        whatsappButton.setOnClickListener{
            var con = itemView.context

            val textToShare = "*כח אדם*"
            val phoneNumber = blogPost.phone
            val sendIntent = Intent()

            sendIntent.action = Intent.ACTION_SEND
            sendIntent.type = "text/plain"
            sendIntent.putExtra("jid", phoneNumber+"@s.whatsapp.net")
            sendIntent.putExtra(Intent.EXTRA_TEXT, textToShare)
            val extra = sendIntent.extras
            startActivity(con,sendIntent,extra)
        }
4

4 Answers

0
votes

If you want send a message to a specific contact from Contacts app, you should first require permission to access contacts, get the number and try with this:

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");
startActivity(sendIntent);

Ref: https://stackoverflow.com/a/40285262/2895571

0
votes

Please check this answer here Use the following bit of code:

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

First option: using Uri to convert whatsapp web url into button:

open_whatsapp.setOnClickListener {

        val url = "https://api.whatsapp.com/send?phone=XXXXXXXXXX"

        val openWhatsappIntent = Intent(Intent.ACTION_VIEW)
        openWhatsappInten.data = Uri.parse(url)
        startActivity(openWhatsappInten)
    }

Second option; this is used as a href in web development :

<a href="https://api.whatsapp.com/send?phone=XXXXXXXX" target="_blank"> Tel: XXX XXXX XX</a>

maybe you can add Html format into TextView (Html.fromHtml()) and enable links clickeable to open the whatsapp application.

0
votes

if you want send message to particular contact in whatsapp , use below url and particular mobile no to the Intent(including Country code).

String url = "https://wa.me/"; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url+mobile_no)); startActivity(browserIntent);