How to open WhatsApp using an Intent in your Android App
Asked Answered
M

21

58

I want an Intent to take control you directly to WhatsApp. So the moment the user clicks on the button, the Intent is supposed to take you to WhatsApp. This is the code I wrote after following a few guide lines but it doesn't work

buttonWhatsapp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Performs action on click
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
            sendIntent.setType("text/plain");
            sendIntent.setPackage("com.whatsapp");
            startActivity(Intent.createChooser(sendIntent, ""));
            startActivity(sendIntent);
            //opens the portfolio details class
        }
    });
Marlinmarline answered 17/7, 2016 at 14:28 Comment(0)
D
97

Using the 2018 api:

String url = "https://api.whatsapp.com/send?phone="+number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Degeneration answered 27/8, 2018 at 10:29 Comment(7)
It worked for me. Want to mention that I needed to send the number in the format of +00 0000000000 – Henslowe
If WhatsApp is not installed on the device, it will open a web browser to handle this. Nice! – Qulllon
I've opened this URL with my number in my mobile browser. I've my own chat now, which will make non IT people go wow πŸ˜‚ – Osbourne
This is better, because do not need the Whatsapp Installed on App – Sonnier
to add message you have to use "https://api.whatsapp.com/send?phone=$phoneNumber"+"&text=" + URLEncoder.encode(message, "UTF-8") – Racket
how I can make it not open browser when the app is not installed ? – Overhappy
@sattar check if whatsapp is installed, before passing the intent to the OS – Maddocks
E
42

This code working for me

String contact = "+00 9876543210"; // use country code with your phone number
    String url = "https://api.whatsapp.com/send?phone=" + contact;
    try {
         PackageManager pm = context.getPackageManager();
         pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
         Intent i = new Intent(Intent.ACTION_VIEW);
         i.setData(Uri.parse(url));
         startActivity(i);                            
    } catch (PackageManager.NameNotFoundException e) {
    Toast.makeText(MainActivity.activity, "Whatsapp app not installed in your phone", Toast.LENGTH_SHORT).show();
    e.printStackTrace();
    }
Ethmoid answered 10/11, 2018 at 17:44 Comment(1)
on Android 11 you also need to add <queries> <package android:name="com.whatsapp" /> </queries> on manifest – Nonjoinder
L
18

This works perfectly 2021

Expansion of short forms:

numero = number phone

mensaje= message to send

private void openWhatsApp(String numero,String mensaje){

    try{
        PackageManager packageManager = getActivity().getPackageManager();
        Intent i = new Intent(Intent.ACTION_VIEW);
        String url = "https://api.whatsapp.com/send?phone="+ numero +"&text=" + URLEncoder.encode(mensaje, "UTF-8");
        i.setPackage("com.whatsapp");
        i.setData(Uri.parse(url));
        if (i.resolveActivity(packageManager) != null) {
            startActivity(i);
        }else {
            KToast.errorToast(getActivity(), getString(R.string.no_whatsapp), Gravity.BOTTOM, KToast.LENGTH_SHORT);
        }
    } catch(Exception e) {
        Log.e("ERROR WHATSAPP",e.toString());
        KToast.errorToast(getActivity(), getString(R.string.no_whatsapp), Gravity.BOTTOM, KToast.LENGTH_SHORT);
    }

}

Hope, This Helps!

Lubalubba answered 5/10, 2018 at 17:31 Comment(0)
R
15

Feb 2024
πŸ‘ Just a little more peachy answer:
Don't forget to add the country code before the number, I mean use the full phone number in international format, without leading zeros, brackets, or dashes. (+1...)

public static void setClickToChat(View v,String toNumber){
    String url = "https://api.whatsapp.com/send?phone=" + toNumber;
    try {
        PackageManager pm = v.getContext().getPackageManager();
        pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        v.getContext().startActivity(i);
    } catch (PackageManager.NameNotFoundException e) {
        v.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }
}

Kotlin View extension function :

fun View.openWhatsAppChat(toNumber: String) {
   val url = "https://api.whatsapp.com/send?phone=$toNumber"
   try {
       context.packageManager.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES)
       context.startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(url) })
   } catch (e: PackageManager.NameNotFoundException) {
       context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))}}

Jetpack Compose :

val toNumber = "+123456789"
val msg = "Hello from Stackoverflow!"
val url = "https://api.whatsapp.com/send?phone=$toNumber"
val context = LocalContext.current
val packageManager = LocalContext.current.packageManager
val intent: Intent = try {
    Intent(Intent.ACTION_SEND).apply {
        type = "text/plain"
        putExtra(Intent.EXTRA_TEXT, msg)
        putExtra(Intent.EXTRA_PHONE_NUMBER, toNumber)
        val info = packageManager.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA)
        `package` = "com.whatsapp"
    }
} catch (e: PackageManager.NameNotFoundException) {
    Intent(Intent.ACTION_VIEW, Uri.parse(url))
}

Button(
    onClick = {
        context.startActivity(intent)
    }
) { Text(text = "Open WhatsApp",) }
Regardful answered 4/3, 2021 at 7:48 Comment(6)
We need to append +91 (country code) and then number to make it work. e.g +919876543210 (dummy number) – Debera
I have tried it, but just opening send to screen of whatsapp – Herbivore
@LalitJadav Have you entered the recipient's number correctly (with country code)? – Regardful
yes, but not worked for audio file – Herbivore
What if there's no country code with the number, how would we get whatsapp to start the chat? – Headrail
@hemaezzat No worries, country code or not, just use the full phone number in international format (without leading zeros, brackets, or dashes) to start a WhatsApp chat – Regardful
D
7

The easiest way i know is by calling the following method (Use the String variable (message) to input the text you want to send via WhatAapp):

private void sendWhatsapp(String message){
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, message);
    sendIntent.setType("text/plain");
    sendIntent.setPackage("com.whatsapp");
    if (sendIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(sendIntent);
    }
}

I hope this helps you.

Decameter answered 22/6, 2017 at 18:11 Comment(1)
how you can add phone number here ? – Overhappy
N
7
btnWhatsapp.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                startSupportChat ();
            }
        } );

private void startSupportChat() {

        try {
            String headerReceiver = "";// Replace with your message.
            String bodyMessageFormal = "";// Replace with your message.
            String whatsappContain = headerReceiver + bodyMessageFormal;
            String trimToNumner = "+910000000000"; //10 digit number
            Intent intent = new Intent ( Intent.ACTION_VIEW );
            intent.setData ( Uri.parse ( "https://wa.me/" + trimToNumner + "/?text=" + "" ) );
            startActivity ( intent );
        } catch (Exception e) {
            e.printStackTrace ();
        }

    }
Nephology answered 23/4, 2019 at 5:21 Comment(0)
B
5

In Kotlin, this is how you would do it.

Open Specific user WhatsApp Number and send a typed message

startActivity(
        Intent(
            Intent.ACTION_VIEW,
            Uri.parse(
                "https://api.whatsapp.com/send?phone=Phone Number&text=Message to send"
            )
        )
    )
Bickering answered 22/4, 2021 at 8:41 Comment(0)
P
4

This is working method. To call this method call like

call like this - openWhatsApp(919876543210)

 private void openWhatsApp(String smsNumber) {
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi, This is " + PreferenceManager.get(this, Constants.USERNAME));
    sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
    sendIntent.setPackage("com.whatsapp");
    if (sendIntent.resolveActivity(getPackageManager()) == null) {
        Toast.makeText(this, "Error/n", Toast.LENGTH_SHORT).show();
        return;
    }
    startActivity(sendIntent);
}
Planetstruck answered 23/4, 2019 at 4:59 Comment(0)
B
3

Hey this snippet is from the official whatsapp site

https://www.whatsapp.com/faq/android/28000012

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
Bharal answered 17/7, 2016 at 14:49 Comment(2)
yep, I know that and thats what I wrote first but it doesn't work – Marlinmarline
It's working, but then you have to manually, select target receiver. – Lazes
L
2
 PackageManager pm = getActivity().getPackageManager();

    try
    {
        // Raise exception if whatsapp doesn't exist
        PackageInfo info = pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");
        waIntent.setPackage("com.whatsapp");
        waIntent.putExtra(Intent.EXTRA_TEXT, "YOUR TEXT");
        startActivity(waIntent);
    }
    catch (PackageManager.NameNotFoundException e)
    {
        Toast.makeText(MainActivity.activity, "Please install whatsapp app", Toast.LENGTH_SHORT)
                .show();
    }
Longford answered 17/7, 2016 at 14:32 Comment(3)
yea I will try it now – Marlinmarline
@ Ali Gürelli It says that it cannot resolve the symbol activity – Marlinmarline
It now has an error that it cannot resolve the method getActivity() – Marlinmarline
D
2

I am showing you how to share text and image both here, For sharing text you can use these code ,

private void shareTextUrl() {
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("text/plain");
    share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    // Add data to the intent, the receiving app will decide
    // what to do with it.
    share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
    share.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");

    startActivity(Intent.createChooser(share, "Share link!"));
}

Now if you want to share image then you can use these code ,

private void shareImage() {
    Intent share = new Intent(Intent.ACTION_SEND);

    // If you want to share a png image only, you can do:
    // setType("image/png"); OR for jpeg: setType("image/jpeg");
    share.setType("image/*");

    // Make sure you put example png image named myImage.png in your
    // directory
    String imagePath = Environment.getExternalStorageDirectory()
            + "/myImage.png";

    File imageFileToShare = new File(imagePath);

    Uri uri = Uri.fromFile(imageFileToShare);
    share.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(share, "Share Image!"));
}
Dozier answered 17/7, 2016 at 14:37 Comment(0)
C
2

this solution work for me :)

 val url = "https://wa.me/WHATSAPP_NUMBER"
        val i = Intent(Intent.ACTION_VIEW)
        i.data = Uri.parse(url)
        startActivity(i)
Confute answered 9/8, 2021 at 20:0 Comment(0)
O
2

My code is a little bit the same but I handled this in a very effective way that runs in all devices up to API 30+ you can try this

//to open whats app app
    fun openApp(activity: Activity,packageName:String) {

        if (isAppInstalled(activity, packageName))
            activity.startActivity(activity.packageManager.getLaunchIntentForPackage(packageName))
        else
            Toast.makeText(activity, "App not installed", Toast.LENGTH_SHORT).show()
    }

    fun isAppInstalled(activity: Activity, packageName: String?): Boolean {
        val pm = activity.packageManager
        try {
            pm.getPackageInfo(packageName!!, PackageManager.GET_ACTIVITIES)
            return true
        } catch (e: PackageManager.NameNotFoundException) {
            Log.e("isAppInstalled", "error :${e.message}")
        }
        return false
    }

In AndroidManifest.xml outside of the application scope just add this query

<manifest>

/*user permissions here whatever you want according to your need*/

    <queries>
             <package android:name="com.whatsapp"/>
             <package android:name="com.whatsapp.w4b"/>
             <package android:name="com.gbwhatsapp"/>
        </queries>
<application> /*here you have registered your activities*/ </application>
</manifest>

I hope this will help anyone you find helpful vote me up. Remember me in your prayer.

Offcenter answered 23/10, 2022 at 19:5 Comment(0)
H
1

this work for this days ago

 private void openWhatsApp(String number) {
    try {
        number = number.replace(" ", "").replace("+", "");

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

        startActivity(Intent.createChooser(sendIntent, "Compartir en")
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

    } catch(Exception e) {
        Log.e("WS", "ERROR_OPEN_MESSANGER"+e.toString());
    }
}
Hardboiled answered 16/10, 2019 at 15:51 Comment(1)
what is jid for? – Suppose
S
1

For Business Whatsapp and normal Whatsapp:

To handle both business whatsapp and normal whatsapp, the url scheme intent needs to be used, since the normal method of using package "com.whatsapp" only works for normal whatsapp.

Here's the code sample to handle both normal and business whatsapp :

try {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse("whatsapp://send?text=The text message goes here");
        context.startActivity(i);
    } catch (Exception e){
        Toast.makeText(context, "Whatsapp not installed!", Toast.LENGTH_LONG).show();
    }

This will open a chooser if both whatsapp are installed and if only either one of them is installed that particular version will be launched.

Sweeny answered 14/2, 2021 at 14:10 Comment(0)
M
1

This code worked for me.

public void openWhatsapp(View view) {
    String message = mMessOpenWhatEdit.getText().toString();     // take message from the user

    // create an Intent to send data to the whatsapp
    Intent intent = new Intent(Intent.ACTION_VIEW);    // setting action

    // setting data url, if we not catch the exception then it shows an error
    try {
        String url = "https://api.whatsapp.com/send?phone=+91 0000000000" + "&text=" + URLEncoder.encode(message, "UTF-8");
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }
    catch(UnsupportedEncodingException e){
        Log.d("notSupport", "thrown by encoder");
    }
}
Maki answered 11/12, 2021 at 6:23 Comment(1)
openWhatsapp is a onclick method(I mean it is called after clicking button in ui) – Maki
G
1

If you want to launch/open WhatsApp application or WhatsApp Business application in android on button click then follow these code.

Launch WhatsApp Business application:

public void launchWhatsAppBusinessApp(View v)
{ 
   PackageManager pm = getPackageManager();
   try
   {
      
       Intent intent = this.getPackageManager().getLaunchIntentForPackage("com.whatsapp.w4b");
       startActivity(intent);
       }
catch (PackageManager.NameNotFoundException e)
       {
           Toast.makeText(this, "Please install WA Business App", Toast.LENGTH_SHORT).show();
       }
catch(NullPointerException exception){}
   }

Launch WhatsApp application:

public void openWhatsApp(View v)
{
    PackageManager pm = getPackageManager();
    try
    {
        
        Intent intent = this.getPackageManager().getLaunchIntentForPackage("com.whatsapp");
        startActivity(intent);
    }
    catch (PackageManager.NameNotFoundException e)
    {
        Toast.makeText(this, "Please install WhatsApp App", Toast.LENGTH_SHORT).show();
    }
    catch(NullPointerException exception){}

}
Gilthead answered 6/4, 2022 at 18:11 Comment(0)
C
1

You can use below code snipped for kotin.

try {
                val sendIntent = Intent().apply {
                    action = Intent.ACTION_SEND
                    putExtra(Intent.EXTRA_TEXT, "Hello Swapz")
                    putExtra("jid", "${data.phone}@s.whatsapp.net")
                    type = "text/plain"
                    setPackage("com.whatsapp")
                }
                startActivity(sendIntent)
            }catch (e: Exception){
                e.printStackTrace()
               val appPackageName = "com.whatsapp"
                try {
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName")))
                } catch (e :android.content.ActivityNotFoundException) {
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")))
                }
            }
Crafty answered 24/10, 2022 at 20:15 Comment(0)
L
1
tvWhatsapp.setOnClickListener(v -> {

   Intent intent = new Intent(Intent.ACTION_VIEW);
   intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=+......."));
   startActivity(intent);

});
Laughter answered 27/9, 2023 at 6:59 Comment(0)
V
0

only wants to open whatsApp in kotlin in activity

val packagename = "com.whatsapp" val intent = packagemanager.getLaunchIntentForPackage("packagename") intent?. let{startActivity(it)}

change only packages for others application for whatsapp business

packagename ="com.whatsapp.w4b"

in Fragment use requiredActivity(). packagemanager instead of packagemanager

Ventilate answered 21/12, 2023 at 8:48 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center. – Cimino
S
0

In 2024 you can achieve this like that

/**
* Using Java
*/ 


     String mapUrl = "https://www.google.com/maps?q=" + latitude + "," + longitude;

                String message = "Consulta mi ubicaciΓ³n en Google Maps: " + mapUrl;
              
                String url = "https://api.whatsapp.com/send?phone=" + contact.getPhone()+"&text="+message;

                try {
                    PackageManager pm = v.getContext().getPackageManager();
                    pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    i.putExtra(Intent.EXTRA_TEXT, message);
                    v.getContext().startActivity(i);
                } catch (PackageManager.NameNotFoundException e) {
                    v.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                }

 /**
 * Using Kotlin
 */ 

    val mapUrl = "https://www.google.com/maps?q=$latitude,$longitude"

val message = "Consulta mi ubicaciΓ³n en Google Maps: $mapUrl"

val url = "https://api.whatsapp.com/send?phone=${contact.phone}&text=${Uri.encode(message)}"

try {
    val pm = v.context.packageManager
    pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES)
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse(url)
    intent.putExtra(Intent.EXTRA_TEXT, message)
    v.context.startActivity(intent)
} catch (e: PackageManager.NameNotFoundException) {
    v.context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
 
Shipyard answered 3/5, 2024 at 19:9 Comment(0)

© 2022 - 2025 β€” McMap. All rights reserved.