以编程方式将文本发送到特定联系人(whatsapp)

Com*_*Guy 55 android contact android-intent whatsapp

我想知道如何将文本发送到特定的WhatsApp联系人.我找到了一些代码来查看特定联系人,但不发送数据.

Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
    new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
    new String[] { id }, null);
c.moveToFirst();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));

startActivity(i);
c.close();
Run Code Online (Sandbox Code Playgroud)

这适用于查看whatsapp-contact,但我现在如何添加一些文本?或者Whatsapp开发人员没有实现这样的api?

Chr*_*ipp 65

我认为答案是你的问题和这个答案的混合:https://stackoverflow.com/a/15931345/734687 所以我会尝试以下代码:

  1. 将ACTION_VIEW更改为ACTION_SENDTO
  2. 像你一样设置Uri
  3. 将包设置为whatsapp
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);
Run Code Online (Sandbox Code Playgroud)

我查看了Whatsapp清单,发现ACTION_SEND已注册到活动中ContactPicker,因此无法帮助您.但是ACTION_SENDTO已注册到活动中com.whatsapp.Conversation,这听起来更适合您的问题.

Whatsapp可以作为发送短信的替代品,所以它应该像短信一样工作.如果未指定所需的应用程序(通过setPackage),Android将显示应用程序选择器.因此,您应该查看通过意图发送SMS的代码,然后提供其他包信息.

Uri uri = Uri.parse("smsto:" + smsNumber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra("sms_body", smsText);  
i.setPackage("com.whatsapp");  
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

首先尝试将意图替换ACTION_SENDACTION_SENDTO.如果这不起作用,则提供额外的额外费用sms_body.如果这不起作用,请尝试更改uri.

更新 我试图自己解决这个问题,但无法找到解决方案.Whatsapp打开聊天记录,但不接收文本并发送.似乎这个功能没有实现.

  • 只打开联系人,但没有文本传递给Whatsapp ...似乎Whatsapp不识别那些额外的(或不想要的). (6认同)
  • 它告诉我电话号码没有Wha​​tsApp,即使有。有什么办法我应该首先格式化它? (2认同)
  • 请阅读我对这个问题的回答,它可以在不包含在您的联系人列表中的情况下起作用。完美运作。 (2认同)

Cro*_*ono 58

我找到了正确的方法,这很简单,你只需要阅读这篇文章:http://howdygeeks.com/send-whatsapp-message-unsaved-number-android/

源代码:phone并且message都是String.

    PackageManager packageManager = context.getPackageManager();
    Intent i = new Intent(Intent.ACTION_VIEW);

    try {
        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();
    }
Run Code Online (Sandbox Code Playgroud)

请享用!

  • 这是一个,如果以前未将联系人添加到电话中,则最不能支持。 (2认同)
  • 不发送文本,只是打开消息聊天,但不发送文本。 (2认同)
  • 如@PabloQuemé所说,如果您以前没有添加此联系人,则会有一个呼出消息说您没有此联系人。所以我只发送了电话号码,但是当我将完整的电话号码添加到国家(地区)代码后,效果很好! (2认同)
  • 在号码前添加国家/地区代码,例如+91、+1、+44 等将打开该人的聊天屏幕。 (2认同)

小智 55

我已经做了!

private void openWhatsApp() {
    String smsNumber = "7****"; // E164 format without '+' sign
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
    sendIntent.setPackage("com.whatsapp");
    if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
        Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
        return;    
    }
    startActivity(sendIntent);
}
Run Code Online (Sandbox Code Playgroud)

  • 有效,但电话号码应添加到设备联系人列表中 (4认同)
  • 我对你的解决方案持怀疑态度,因为它没有得到很多赞成票。但它有效! (2认同)
  • 它用特定的聊天文本打开特定的联系号码但不发送它,用户必须按发送按钮发送消息.+1对特定活动开放投票. (2认同)
  • 这个真的有效!找到一种使用应用程序选择器的方法并且仍然包含消息文本和电话号码,以便用户可以选择 SMS 和 Whatsapp 选项也很高兴......有人吗? (2认同)
  • 这仅在某些设备中不起作用 (2认同)

Pio*_*eer 21

这种方法也适用于WhatsApp Business应用程序!

将包名更改为sendIntent.setPackage("com.whatsapp.w4b"); 为WhatsApp业务.

非常好的黑客Rishabh,非常感谢,自从过去3年以来我一直在寻找这个解决方案.

根据Rishabh Maurya上面的回答,我已经实现了这个代码,它在WhatsApp上的文本和图像共享都很好.

请注意,在这两种情况下,它都会打开一个whatsapp会话(如果toNumber存在于用户whatsapp联系人列表中),但用户必须单击"发送"按钮才能完成操作.这意味着它有助于跳过联系人选择步骤.

用于短信

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);
Run Code Online (Sandbox Code Playgroud)

用于共享图像

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);
Run Code Online (Sandbox Code Playgroud)

享受WhatsApping!

  • 不为我工作。它正在打开联系人选择屏幕。 (2认同)

Pra*_*tha 15

它允许您为您尝试与之通信的特定用户打开WhatsApp对话屏幕:

private void openWhatsApp() {
    String smsNumber = "91XXXXXXXX20";
    boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
    if (isWhatsappInstalled) {

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

        startActivity(sendIntent);
    } else {
        Uri uri = Uri.parse("market://details?id=com.whatsapp");
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        Toast.makeText(this, "WhatsApp not Installed",
                Toast.LENGTH_SHORT).show();
        startActivity(goToMarket);
    }
}

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;
}
Run Code Online (Sandbox Code Playgroud)


Ris*_*rya 10

看看我的答案:https://stackoverflow.com/a/40285262/5879376

 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");//phone number without "+" prefix

 startActivity(sendIntent);
Run Code Online (Sandbox Code Playgroud)


小智 6

这将首先搜索指定的联系人,然后打开聊天窗口.如果没有安装WhatsApp,那么try-catch块处理这个.

 String digits = "\\d+";
    Sring mob_num = 987654321;     
    if (mob_num.matches(digits)) 
            {
        try {
              /linking for whatsapp
              Uri uri = Uri.parse("whatsapp://send?phone=+91" + mob_num);
              Intent i = new Intent(Intent.ACTION_VIEW, uri);
              startActivity(i);
            }
            catch (ActivityNotFoundException e){
                    e.printStackTrace();
                    Toast.makeText(this, "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
            }
        }
Run Code Online (Sandbox Code Playgroud)


Ram*_*mar 6

我正在尝试使用另一个应用程序在 WhatsApp 中发送短信。

假设我们有一个按钮,在按钮上单击您调用下面的方法。

sendTextMsgOnWhatsApp("+91 9876543210", "你好,这是我的测试消息");

public void sendTextMsgOnWhatsApp(String sContactNo, String sMessage) {
        String toNumber = sContactNo; // contains spaces, i.e., example +91 98765 43210
        toNumber = toNumber.replace("+", "").replace(" ", "");

        /*this method contactIdByPhoneNumber() will get unique id for given contact,
        if this return's null then it means that you don't have any contact save with this mobile no.*/
        String sContactId = contactIdByPhoneNumber(toNumber);

        if (sContactId != null && sContactId.length() > 0) {

            /*
             * Once We get the contact id, we check whether contact has a registered with WhatsApp or not.
             * this hasWhatsApp(hasWhatsApp) method will return null,
             * if contact doesn't associate with whatsApp services.
             * */
            String sWhatsAppNo = hasWhatsApp(sContactId);

            if (sWhatsAppNo != null && sWhatsAppNo.length() > 0) {
                Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
                sendIntent.putExtra(Intent.EXTRA_TEXT, sMessage);
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setPackage("com.whatsapp");
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            } else {
                // this contact does not exist in any WhatsApp application
                Toast.makeText(this, "Contact not found in WhatsApp !!", Toast.LENGTH_SHORT).show();
            }
        } else {
            // this contact does not exist in your contact
            Toast.makeText(this, "create contact for " + toNumber, Toast.LENGTH_SHORT).show();
        }
    }

    private String contactIdByPhoneNumber(String phoneNumber) {
        String contactId = null;
        if (phoneNumber != null && phoneNumber.length() > 0) {
            ContentResolver contentResolver = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            String[] projection = new String[]{ContactsContract.PhoneLookup._ID};

            Cursor cursor = contentResolver.query(uri, projection, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
                }
                cursor.close();
            }
        }
        return contactId;
    }

    public String hasWhatsApp(String contactID) {
        String rowContactId = null;
        boolean hasWhatsApp;

        String[] projection = new String[]{ContactsContract.RawContacts._ID};
        String selection = ContactsContract.RawContacts.CONTACT_ID + " = ? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " = ?";
        String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
        Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
        if (cursor != null) {
            hasWhatsApp = cursor.moveToNext();
            if (hasWhatsApp) {
                rowContactId = cursor.getString(0);
            }
            cursor.close();
        }
        return rowContactId;
    }
Run Code Online (Sandbox Code Playgroud)

在AndroidManifest.xml文件中添加以下权限

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)


Kir*_*eph 5

Whatsapp have its own API

    Intent sendIntent = new Intent("android.intent.action.MAIN");
                        sendIntent.setAction(Intent.ACTION_VIEW);
                        sendIntent.setPackage("com.whatsapp");
                        String url = "https://api.whatsapp.com/send?phone=" + "Phone with international format" + "&text=" + "your message";
                        sendIntent.setData(Uri.parse(url));
                        if(sendIntent.resolveActivity(context.getPackageManager()) != null){
                             startActivity(sendIntent);
                        }
Run Code Online (Sandbox Code Playgroud)

Code updated check added for Activity is available or not.

See this documentation

  • 在 whatsapp 版本 2.18.380 上为我工作 (2认同)

Com*_*Guy 3

现在可以通过WhatsApp Business API实现这一点。只有企业可以申请使用。这是直接向电话号码发送消息而无需任何人工交互的唯一方法。

发送普通消息是免费的。看起来您需要在服务器上托管 MySQL 数据库和 WhatsApp Business 客户端。