How can I send message to specific contact through WhatsApp from my android app?

前端 未结 13 1527
梦毁少年i
梦毁少年i 2020-12-02 17:41

I am developing an android app and I need to send a message to specific contact from WhatsApp. I tried this code:

Uri mUri = Uri.parse(\"smsto:+999999999\");         


        
相关标签:
13条回答
  • 2020-12-02 18:34

    This is what works for me.

    The parameter 'body' gets not red by the whatsapp app, use 'Intent.EXTRA_TEXT' instead.

    By setting the 'phoneNumber' you specify the contact to open in whatsapp.

    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, 
           Uri.parse("smsto:" + "" + phoneNumber + "?body=" + encodedMessage));
    sendIntent.putExtra(Intent.EXTRA_TEXT, message);
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent);
    
    0 讨论(0)
  • 2020-12-02 18:35

    I found the right way to do this and is just simple after you read this article: http://howdygeeks.com/send-whatsapp-message-unsaved-number-android/

    phone and message are both String.

    Source code:

    try {
    
        PackageManager packageManager = context.getPackageManager();
        Intent i = new Intent(Intent.ACTION_VIEW);
    
        String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
        i.setPackage("com.whatsapp");
        i.setData(Uri.parse(url));
        if (i.resolveActivity(packageManager) != null) {
            context.startActivity(i);
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    

    Enjoy!

    0 讨论(0)
  • 2020-12-02 18:35

    Here's my way to do it (more here):

    First, if you want to be sure you can send the message, you can check if the person has a WhatsApp account on the address book:

    @RequiresPermission(permission.READ_CONTACTS)
    public String getContactMimeTypeDataId(@NonNull Context context, String contactId, @NonNull String mimeType) {
        if (TextUtils.isEmpty(mimeType) || !PermissionUtil.hasPermissions(context, Manifest.permission.READ_CONTACTS))
            return null;
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{Data._ID}, Data.MIMETYPE + "= ? AND "
                + ContactsContract.Data.CONTACT_ID + "= ?", new String[]{mimeType, contactId}, null);
        if (cursor == null)
            return null;
        if (!cursor.moveToFirst()) {
            cursor.close();
            return null;
        }
        String result = cursor.getString(cursor.getColumnIndex(Data._ID));
        cursor.close();
        return result;
    }
    

    and if all seem well, you open it as if it's from the web:

                final String contactMimeTypeDataId = getContactMimeTypeDataId(context, contactId, "vnd.android.cursor.item/vnd.com.whatsapp.profile");
                if (contactMimeTypeDataId != null) {
                    final String whatsAppPhoneNumber = PhoneNumberHelper.normalizePhone(phoneNumber);
                    String url = "https://api.whatsapp.com/send?phone="+ whatsAppPhoneNumber ;
                    intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
                    intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
                    .setPackage("com.whatsapp");
                    startActivity(intent);
                }
    

    You can also check if WhatsApp is even installed before of all of this (or remove the setPackage and check if any app can handle the Intent) :

            final PackageManager packageManager = context.getPackageManager();
            final ApplicationInfo applicationInfo = packageManager.getApplicationInfo("com.whatsapp", 0);
            if (applicationInfo == null)
               return;
    

    EDIT: about preparing the Intent with the Uri, I think this way is better:

        @JvmStatic
        fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
    //     example url: "https://api.whatsapp.com/send?phone=normalizedPhoneNumber&text=abc"
            val builder = Uri.Builder().scheme("https").authority("api.whatsapp.com").path("send")
            normalizedPhoneNumber?.let { builder.appendQueryParameter("phone", it) }
            message?.let { builder.appendQueryParameter("text", it) }
            return Intent(Intent.ACTION_VIEW, builder.build())
        }
    

    or alternative (based on here):

        fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
    //     example url: "https://wa.me/normalizedPhoneNumber&text=abc"
            val builder = Uri.Builder().scheme("https").authority("wa.me")
            normalizedPhoneNumber?.let { builder.appendPath(it) }
            message?.let { builder.appendQueryParameter("text", it) }
            return Intent(Intent.ACTION_VIEW, builder.build())
        }
    
    0 讨论(0)
  • 2020-12-02 18:36

    Great hack Rishabh, thanks a lot, I was looking for this solution since last 3 years.

    As per the Rishabh Maurya's answer above, I have implemented this code which is working fine for both text and image sharing on WhatsApp. I have published this in my android app, so if you want to see it live try my app Bill Book

    Note that in both the cases it opens a whatsapp conversation (if toNumber exists in users whatsapp contact list), but user have to click send button to complete the action. That means it helps in skipping contact selection step.

    For text messages

    String toNumber = "+91 98765 43210"; // contains spaces.
    toNumber = toNumber.replace("+", "").replace(" ", "");
    
    Intent sendIntent = new Intent("android.intent.action.MAIN");
    sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
    sendIntent.putExtra(Intent.EXTRA_TEXT, message);
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.setPackage("com.whatsapp");
    sendIntent.setType("text/plain");
    startActivity(sendIntent);
    

    For sharing images

    String toNumber = "+91 98765 43210"; // contains spaces.
    toNumber = toNumber.replace("+", "").replace(" ", "");
    
    Intent sendIntent = new Intent("android.intent.action.MAIN");
    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
    sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
    sendIntent.putExtra(Intent.EXTRA_TEXT, message);
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.setPackage("com.whatsapp");
    sendIntent.setType("image/png");
    context.startActivity(sendIntent);
    

    Enjoy WhatsApping!

    0 讨论(0)
  • 2020-12-02 18:36
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_VIEW); 
    String url ="https://wa.me/your number"; 
    sendIntent.setData(Uri.parse(url));
    startActivity(sendIntent);
    
    0 讨论(0)
  • 2020-12-02 18:40

    you can use this code:

     Intent sendIntent = new Intent("android.intent.action.MAIN");
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.setPackage("com.whatsapp");
    sendIntent.setType("text/plain");
    sendIntent.putExtra("jid", "9194******22" + "@s.whatsapp.net");// here 91 is country code
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Demo test message");
    startActivity(sendIntent);
    
    0 讨论(0)
提交回复
热议问题