55

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
        }
    });
Prateek Mahesh
  • 665
  • 1
  • 6
  • 10

18 Answers18

95

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);
Pablo Cegarra
  • 20,955
  • 12
  • 92
  • 110
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();
    }
GS Nayma
  • 1,745
  • 19
  • 24
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!

Sam Joshua
  • 310
  • 6
  • 17
Marlon Viana
  • 191
  • 1
  • 2
9

Just a little more peachy answer (May 2023):

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)));
    }
}
ucMedia
  • 4,105
  • 4
  • 38
  • 46
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.

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 ();
        }

    }
Unnati Patadia
  • 662
  • 3
  • 19
  • 39
4

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"
            )
        )
    )
Kimanthi K.
  • 595
  • 6
  • 13
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);
SaravInfern
  • 3,338
  • 1
  • 20
  • 44
3

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);
}
AMAN SINGH
  • 3,491
  • 6
  • 28
  • 44
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();
    }
aligur
  • 3,387
  • 3
  • 34
  • 51
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!"));
}
Shubham Sharma
  • 2,763
  • 5
  • 31
  • 46
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)
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.

Mohammed Junaid
  • 1,362
  • 14
  • 18
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");
    }
}
Kanha Tomar
  • 199
  • 1
  • 9
0

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());
    }
}
joe06
  • 418
  • 4
  • 17
0

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){}

}
Community
  • 1
  • 1
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
0

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.

0

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")))
                }
            }
Emre Gürses
  • 1,992
  • 1
  • 23
  • 28