简体   繁体   English

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

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

I am developing an android app and I need to send a message to specific contact from WhatsApp.我正在开发一个 android 应用程序,我需要从 WhatsApp 向特定联系人发送消息。 I tried this code:我试过这个代码:

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”。

There is a way.有办法。 Make sure that the contact you are providing must be passed as a string in intent without the prefix "+".确保您提供的联系人必须作为字符串在 Intent 中传递,不带前缀“+”。 Country code should be appended as a prefix to the phone number .国家/地区代码应作为电话号码的前缀附加。

eg: '+918547264285' should be passed as '918547264285' .例如: '+918547264285' 应该作为 '918547264285' 传递。 Here '91' in beginning is country code .这里开头的 '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);

Update:更新:

The aforementioned hack cannot be used to add any particular message, so here is the new approach.前面提到的 hack 不能用于添加任何特定的消息,所以这里是新方法。 Pass the user mobile in international format here without any brackets, dashes or plus sign.在此处以国际格式传递用户手机,不带任何括号、破折号或加号。 Example: If the user is of India and his mobile number is 94xxxxxxxx , then international format will be 9194xxxxxxxx .示例:如果用户是印度人,他的手机号码是94xxxxxxxx ,那么国际格式将是9194xxxxxxxx Don't miss appending country code as a prefix in mobile number.不要错过在手机号码中附加国家代码作为前缀。

  private fun sendMsg(mobile: String, msg: String){
    try {
        val packageManager = requireContext().packageManager
        val i = Intent(Intent.ACTION_VIEW)
        val url =
            "https://wa.me/$mobile" + "?text=" + URLEncoder.encode(msg, "utf-8")
        i.setPackage("com.whatsapp")
        i.data = Uri.parse(url)
        if (i.resolveActivity(packageManager) != null) {
            requireContext().startActivity(i)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

Note : This approach works only with contacts added in user's Whatsapp account.注意:此方法仅适用于在用户的 Whatsapp 帐户中添加的联系人。

This new method, send message to a specific contact via whatsapp in Android.这种新方法通过 Android 中的 whatsapp 向特定联系人发送消息。 For more information look here欲了解更多信息,请看 这里

            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

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!享受!

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.根据上面 Rishabh Maurya 的回答,我已经实现了这段代码,它适用于 WhatsApp 上的文本和图像共享。 I have published this in my android app, so if you want to see it live try my app Bill Book我已经在我的 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.请注意,在这两种情况下,它都会打开一个 whatsapp 对话(如果用户 whatsapp 联系人列表中存在 toNumber),但用户必须单击发送按钮才能完成操作。 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!享受WhatsApping!

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

This is the best way to send Message through Whatsapp to specific number or unsaved number这是通过 Whatsapp 向特定号码或未保存号码发送消息的最佳方式

private void openWhatsApp() {
    String smsNumber = "252634651588";
    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(getContext(), "WhatsApp not Installed",
                Toast.LENGTH_SHORT).show();
        startActivity(goToMarket);
    }
}

private boolean whatsappInstalledOrNot(String uri) {
    PackageManager pm = Objects.requireNonNull(getContext()).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;
}

We can share/send message to whats app.我们可以分享/发送消息到什么应用程序。 Below is Sample code to send text message on Whats-app以下是在Whats-app上发送短信的示例代码

  1. Single user单用户
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多用户
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();
    }
}

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);
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 上的特定联系人发送消息

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));
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW); 
String url ="https://wa.me/your number"; 
sendIntent.setData(Uri.parse(url));
startActivity(sendIntent);

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:首先,如果您想确保可以发送消息,您可以检查此人是否在地址簿上拥有 WhatsApp 帐户:

@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) :您还可以检查在所有这些之前是否安装了 WhatsApp(或删除setPackage并检查是否有任何应用程序可以处理 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:编辑:关于用 Uri 准备意图,我认为这种方式更好:

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

Try using Intent.EXTRA_TEXT instead of sms_body as your extra key.尝试使用Intent.EXTRA_TEXT而不是sms_body作为您的额外密钥。 Per WhatsApp's documentation, this is what you have to use.根据 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_SEND instead of Intent.ACTION_SENDTO , so I'm not sure if WhatsApp even supports sending directly to a contact via the intent system.他们的示例使用Intent.ACTION_SEND而不是Intent.ACTION_SENDTO ,所以我不确定 WhatsApp 是否支持通过 Intent 系统直接发送给联系人。 Some quick testing should let you determine that.一些快速测试应该可以让您确定这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM