Sapna Sharma
Sapna Sharma

Reputation: 480

Send message to particular contact through WhatsApp in android

I tried so many solution but still no success in sending messages to particular whatsapp contact in my app. Here is my code :

  Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setType("text/plain");
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey");
                sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber) + "@s.whatsapp.net"); 
                sendIntent.setPackage("com.whatsapp");
                mContext.startActivity(sendIntent);

It is just opening particular contact chat window as new conversation with no contact name, profile pic and old conversion.

Please help me to solve this. Also attaching screenshot.

enter image description here

Upvotes: 1

Views: 1089

Answers (2)

Ashish John
Ashish John

Reputation: 1905

Intent sendIntent = new Intent("android.intent.action.MAIN");
        sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey");
        sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("91xxxx008686")+"@s.whatsapp.net");
//phone number without "+" prefix (countrycode & contact number without '+')

        startActivity(sendIntent);

You have missed the set component part which retrieves old conversation from 'Conversation' class.

Upvotes: 0

Amrish Kakadiya
Amrish Kakadiya

Reputation: 1023

I think you want like this.

private void openWhatsApp() {
        String text = message.getText().toString();
        if(whatsappInstalledOrNot("com.whatsapp")){
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("whatsapp://send?text="+text+"&phone="+mobileNumber.getText().toString()));
            startActivity(browserIntent);
        }else {
            Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                    .show();
        }
    }
private boolean whatsappInstalledOrNot(String uri) {
        PackageManager pm = getPackageManager();
        boolean app_installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            app_installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            app_installed = false;
        }
        return app_installed;
    }

Hope this will help.

Upvotes: 4

Related Questions