Java 如何从我的 Android 应用程序通过 WhatsApp 向特定联系人发送消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36344892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:44:36  来源:igfitidea点击:

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

javaandroidandroid-intentwhatsappstart-activity

提问by Johny Moo

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

我正在开发一个 android 应用程序,我需要从 WhatsApp 向特定联系人发送消息。我试过这个代码:

Uri mUri = Uri.parse("smsto:+999999999");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("sms_body", "The text goes here");
mIntent.putExtra("chat",true);
startActivity(mIntent);

The problem is that the parameter "sms_body" is not received on WhatsApp, though the contact is selected.

问题是尽管选择了联系人,但 WhatsApp 未收到参数“sms_body”。

采纳答案by Nathan Walters

Try using Intent.EXTRA_TEXTinstead of sms_bodyas your extra key. Per WhatsApp's documentation, this is what you have to use.

尝试使用Intent.EXTRA_TEXT而不是sms_body作为您的额外密钥。根据 WhatsApp 的文档,这是您必须使用的。

An example from their website:

他们网站上的一个例子:

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

Their example uses Intent.ACTION_SENDinstead of Intent.ACTION_SENDTO, so I'm not sure if WhatsApp even supports sending directly to a contact via the intent system. Some quick testing should let you determine that.

他们的示例使用Intent.ACTION_SEND代替Intent.ACTION_SENDTO,所以我不确定 WhatsApp 是否支持通过意图系统直接发送给联系人。一些快速测试应该可以让您确定这一点。

回答by Rishabh Maurya

There is a way. Make sure that the contact you are providing must be passed as a string in intent without the prefix "+". Country code should be appended as a prefix to the phone number .

有一种方法。确保您提供的联系人必须作为字符串在 Intent 中传递,不带前缀“+”。国家/地区代码应作为电话号码的前缀附加。

e.g.: '+918547264285' should be passed as '918547264285' . Here '91' in beginning is country code .

例如: '+918547264285' 应该作为 '918547264285' 传递。这里开头的 '91' 是国家代码。

Note :Replace the 'YOUR_PHONE_NUMBER' with contact to which you want to send the message.

注意:将“YOUR_PHONE_NUMBER”替换为您要向其发送消息的联系人。

Here is the snippet :

这是片段:

 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");
 startActivity(sendIntent);

回答by Yoraco Gonzales

This is what works for me.

这对我有用。

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

whatsapp 应用程序不会将参数“body”变为红色,请改用“Intent.EXTRA_TEXT”。

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

通过设置“电话号码”,您可以指定要在 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);

回答by Sapna Sahu Panda

Uri mUri = Uri.parse("smsto:+90000900000");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("chat",true);
startActivity(Intent.createChooser(mIntent, "Share with"));

Works great to send message to specific contact on WhatsApp from my android app

非常适合从我的 Android 应用程序向 WhatsApp 上的特定联系人发送消息

回答by Pioneer

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

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

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

根据上面 Rishabh Maurya 的回答,我已经实现了这段代码,它适用于 WhatsApp 上的文本和图像共享。我已经在我的 android 应用程序中发布了这个,所以如果你想现场看到它,试试我的应用程序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.

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

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!

享受WhatsApping!

回答by Crono

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/

我找到了正确的方法,在你阅读这篇文章后很简单: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!

享受!

回答by Pedro Henrique

This new method, send message to a specific contact via whatsapp in Android. For more information look here

这种新方法通过 Android 中的 whatsapp 向特定联系人发送消息。欲了解更多信息,请看这里

            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_VIEW);
            String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + path;
            sendIntent.setData(Uri.parse(url));
            activity.startActivity(sendIntent);here

回答by Rupesh Yadav

We can share/send message to whats app. Below is Sample code to send text message on Whats-app

我们可以分享/发送消息到什么应用程序。以下是发送短信的示例代码Whats-app

  1. Single user
  1. 单用户
private void shareToOneWhatsAppUser(String message) {

    /**
     * NOTE:
     * Message is shared with only one user at a time. and to navigate back to main application user need to click back button
     */
    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);

    //Directly send to specific mobile number...
    String smsNumber = "919900990099";//Number without with country code and without '+' prifix
    whatsappIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix

    if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
        Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
        return;
    }

    startActivity(whatsappIntent);
}
  1. Multiple user
  1. 多用户
private void shareToMultipleWhatsAppUser(String message) {

    /**
     * NOTE:
     *
     * If want to send same message to multiple users then have to select the user to whom you want to share the message & then click send.
     * User navigate back to main Application once he/she select all desired persons and click send button.
     * No need to click Back Button!
     */

    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);

    if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
        Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
        return;
    }

    startActivity(whatsappIntent);
}

One more way to achieve the same

实现相同目标的另一种方法

private void shareDirecctToSingleWhatsAppUser(String message) {

    /**
     * NOTE:
     * Message is shared with only one user at a time. and to navigate back to main application user need to click back button
     */

    //Directly send to specific mobile number...
    String smsNumber = "919900000000";//Intended user`s mobile number with country code & with out '+'

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

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

回答by hemant kamat

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

回答by Herdian Murphy

Try this code

试试这个代码

Uri uri = Uri.parse("smsto:" + "+6281122xxx");
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));

You can't put string directly on putExtra like this

你不能像这样直接把字符串放在 putExtra 上

i.putExtra(Intent.EXTRA_TEXT, "YOUR TEXT");

Change your code and get string from resource like this

更改您的代码并从这样的资源中获取字符串

i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));