127

由于我发现了一些较旧的帖子,表明whatsapp 不支持这一点,我想知道是否发生了变化,是否有办法打开一个带有我通过意图发送的号码的whatsapp“聊天”?

4

25 回答 25

192

更新 请参考https://faq.whatsapp.com/en/android/26000030/?category=5245251

WhatsApp 的点击聊天功能让您无需将电话号码保存在手机通讯录中即可开始与某人聊天。只要您知道此人的电话号码,您就可以创建一个链接,以便您开始与他们聊天。

使用:https ://wa.me/15551234567

不要使用:https ://wa.me/+001-(555)1234567

示例:https ://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

原始答案 这是解决方案

public void onClickWhatsApp(View view) {
    
    PackageManager pm=getPackageManager();
    try {

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");
        String text = "YOUR TEXT HERE";

        PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
        //Check if package exists or not. If not then code 
        //in catch block will be called
        waIntent.setPackage("com.whatsapp");

        waIntent.putExtra(Intent.EXTRA_TEXT, text);
        startActivity(Intent.createChooser(waIntent, "Share with"));
        
   } catch (NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
   }  

}

另见http://www.whatsapp.com/faq/en/android/28000012

于 2013-04-10T16:25:39.010 回答
68

使用此代码,您可以使用给定号码打开 whatsapp 聊天。

void openWhatsappContact(String number) {
    Uri uri = Uri.parse("smsto:" + number);
    Intent i = new Intent(Intent.ACTION_SENDTO, uri);
    i.setPackage("com.whatsapp");  
    startActivity(Intent.createChooser(i, ""));
}
于 2014-04-18T15:16:23.153 回答
25

我找到了以下解决方案,首先你需要whatsapp id:

与此处和其他论坛中的其他线程的报告相匹配,我发现的登录名是某种形式:国际区号开头没有 0 或 + + 电话号码没有第一个 0 + @s.whatsapp.net

例如,如果您居住在荷兰并且电话号码为 0612325032,那么对于没有 0 或 + 的荷兰以及没有 0 的电话号码,它将是 31612325023@s.whatsapp.net -> +31。

public void sendWhatsAppMessageTo(String whatsappid) {

Cursor c = getSherlockActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
        new String[] { whatsappid }, null);
c.moveToFirst();

Intent whatsapp = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
c.close();

 if (whatsapp != null) {

startActivity(whatsapp);      

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

}
于 2013-07-30T00:24:39.970 回答
23

简单的解决方案,试试这个。

String phoneNumberWithCountryCode = "+62820000000";
String message = "Hallo";

startActivity(
    new Intent(Intent.ACTION_VIEW,
        Uri.parse(
            String.format("https://api.whatsapp.com/send?phone=%s&text=%s", phoneNumberWithCountryCode, message)
        )
    )
);
于 2017-09-30T05:02:51.487 回答
17

无论是否安装了 Whatsapp,这都应该有效。

boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
if (isWhatsappInstalled) {
    Uri uri = Uri.parse("smsto:" + "98*********7")
    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Hai Good Morning");
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent);
} else {
    Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
    Uri uri = Uri.parse("market://details?id=com.whatsapp");
    Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    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;
}
于 2014-10-13T07:39:11.637 回答
10

在Marshmallow S5上测试,它可以工作!

    Uri uri = Uri.parse("smsto:" + "phone number with country code");
    Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent); 

这将与一个人直接聊天,如果未安装whatsapp,这将抛出异常,如果whatsapp不知道电话号码,他们将提供通过短信或简单短信发送邀请

于 2016-10-22T11:56:56.263 回答
5

使用此单行代码通过 WhatsApp 发送消息

//NOTE : please use with country code first 2digits without plus signed
try {
      String mobile = "911234567890";
      String msg = "Its Working";
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=" + mobile + "&text=" + msg)));
      }catch (Exception e){
        //whatsapp app not install
     }
于 2019-08-12T13:45:09.107 回答
4

检查设备中是否安装了 WhatsApp 并在 WhatsApp 中启动“点击聊天”:

科特林:

try {
    // Check if whatsapp is installed
    context?.packageManager?.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA)
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/$internationalPhoneNumber"))
    startActivity(intent)
} catch (e: NameNotFoundException) {
    Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}

爪哇:

try {
    // Check if whatsapp is installed
    getPackageManager().getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
    Intent intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/" + internationalPhoneNumber));
    startActivity(intent);
} catch (NameNotFoundException e) {
    Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
}

getPackageInfo()NameNotFoundException如果未安装 WhatsApp,则抛出。

internationalPhoneNumber变量用于访问电话号码。

参考:

于 2020-08-28T15:52:49.250 回答
3

以下代码由 Google Now 应用程序使用,不适用于任何其他应用程序。

我写这篇文章是因为它让我很生气,WhatsApp 不允许任何其他开发人员直接发送消息,除了 Google。

我想让其他自由开发者知道,这种合作正在进行中,而谷歌一直在谈论“对任何人开放”,而 WhatsApp 表示他们不想向开发者提供任何访问权限。

最近 WhatsApp 专门为 Google Now 添加了一个 Intent,如下所示:

Intent intent = new Intent("com.google.android.voicesearch.SEND_MESSAGE_TO_CONTACTS");
intent.setPackage("com.whatsapp");
intent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.VoiceMessagingActivity"));

intent.putExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_CHAT_ID", number);
intent.putExtra("android.intent.extra.TEXT", text);
intent.putExtra("search_action_token", ?????);

我还可以发现“search_action_token”是一个包含 IBinder-Object 的 PendingIntent,它被发送回 Google App 并检查它是否是由 Google Now 创建的。

否则 WhatsApp 将不接受该消息。

于 2015-11-16T22:16:19.093 回答
3

目前,您可以请求的唯一官方 API :GET

https://api.whatsapp.com/send?phone=919773207706&text=Hello

无论如何, WhatsApp 已经运行了一个秘密的 API 程序

于 2018-01-06T10:26:30.167 回答
3

这对我有用:

        Uri uri = Uri.parse("https://api.whatsapp.com/send?phone=" + "<number>" + "&text=" + "Hello WhatsApp!!");
        Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(sendIntent);
于 2019-11-19T09:02:42.163 回答
3

这是通过 发送消息的最新方法Whatsapp,即使接收者的电话号码不在您的Whatsapp聊天或电话Contacts列表中。

private fun openWhatsApp(number: String) {
    try {
        packageManager.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES)
        val intent = Intent(
            Intent.ACTION_VIEW,
            Uri.parse("https://wa.me/$number?text=I'm%20interested%20in%20your%20car%20for%20sale")
        )
        intent.setPackage("com.whatsapp")
        startActivity(intent)
    } catch (e: PackageManager.NameNotFoundException) {
        Toast.makeText(
            this,
            "Whatsapp app not installed in your phone",
            Toast.LENGTH_SHORT
        ).show()
        e.printStackTrace()
    }
}

intent.setPackage("com.whatsapp")将帮助您避免使用选择器打开并Whatsapp直接打开。

重要说明:如果您以catch语句结尾,即使Whatsapp已安装。请添加queries如下manifest.xml

<queries>
   <package android:name="com.whatsapp" />
</queries>

有关更多详细信息,请参阅此答案

于 2021-06-05T09:35:53.290 回答
2

这对我有用:

PackageManager pm = context.getPackageManager();
try {
    pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
    Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName,
                    ri.activityInfo.name));
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, element);

} catch (NameNotFoundException e) {
    ToastHelper.MakeShortText("Whatsapp have not been installed.");
}
于 2014-09-03T10:47:18.283 回答
2

正如文档所说,您可以使用如下 URL:

https://wa.me/15551234567

最后一段是E164 格式的数字

Uri uri = Uri.parse("https://wa.me/15551234567");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
于 2018-07-13T11:30:18.467 回答
2

使用whatsapp的直接网址

String url = "https://api.whatsapp.com/send?phone="+number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
于 2020-05-05T20:39:44.203 回答
2

您需要使用以下格式的 URL...

https://api.whatsapp.com/send?text=text

然后你可以让它发送你想要的任何文本。您还可以选择指定电话号码...

https://api.whatsapp.com/send?text=text&phone=1234

不能做的是使用以下内容:

https://wa.me/send?text=text

你会得到...

我们找不到您要查找的页面

wa.me但是,如果您同时提供电话号码和文本,它将起作用。但是,在大多数情况下,如果您要创建共享链接,您真的不想指明电话号码,因为您希望用户选择某人。在这种情况下,如果您不提供号码并wa.me用作 URL,您的所有共享链接都将失败。 请使用app.whatsapp.com.

于 2020-05-14T19:35:37.153 回答
1

这很长,但工作得很好。享受你的代码:)

 //method used to show IMs
private void show_custom_chooser(String value) {
    List<ResolveInfo> list = null;
    final Intent email = new Intent(Intent.ACTION_SEND);
    email.setData(Uri.parse("sms:"));
    email.putExtra(Intent.EXTRA_TEXT, "" + value);
    email.setType("text/plain"); // vnd.android-dir/mms-sms

    WindowManager.LayoutParams WMLP = dialogCustomChooser.getWindow()
            .getAttributes();
    WMLP.gravity = Gravity.CENTER;
    dialogCustomChooser.getWindow().setAttributes(WMLP);
    dialogCustomChooser.getWindow().setBackgroundDrawable(
            new ColorDrawable(android.graphics.Color.TRANSPARENT));
    dialogCustomChooser.setCanceledOnTouchOutside(true);
    dialogCustomChooser.setContentView(R.layout.about_dialog);
    dialogCustomChooser.setCancelable(true);
    ListView lvOfIms = (ListView) dialogCustomChooser
            .findViewById(R.id.listView1);
    PackageManager pm = getPackageManager();
    List<ResolveInfo> launchables = pm.queryIntentActivities(email, 0);
    // ////////////new
    list = new ArrayList<ResolveInfo>();
    for (int i = 0; i < launchables.size(); i++) {
        String string = launchables.get(i).toString();
        Log.d("heh", string);
//check only messangers
        if (string.contains("whatsapp")) {
            list.add(launchables.get(i));
        }
    }
    Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
    int size = launchables.size();
    adapter = new AppAdapter(pm, list, MainActivity.this);
    lvOfIms.setAdapter(adapter);
    lvOfIms.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            ResolveInfo launchable = adapter.getItem(position);
            ActivityInfo activity = launchable.activityInfo;
            ComponentName name = new ComponentName(
                    activity.applicationInfo.packageName, activity.name);
            email.addCategory(Intent.CATEGORY_LAUNCHER);
            email.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            email.setComponent(name);
            startActivity(email);
            dialogCustomChooser.dismiss();
        }
    });
    dialogCustomChooser.show();

}
于 2015-08-22T08:05:18.930 回答
1

我真的来晚了,但我相信现在我们有更短更好的解决方案来通过 WhatsApp 发送消息。

您可以使用以下命令调用系统选择器,然后选择您将使用哪个应用程序来分享您想要的任何内容。

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

如果您真的需要通过 WhatsApp 发送,您只需执行以下操作(您将跳过系统选择器)

 Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.setType("text/plain");
    // Put this line here
    sendIntent.setPackage("com.whatsapp");
    //
    startActivity(sendIntent);

如果您需要更多信息,可以在这里找到:WhatsApp 常见问题

于 2016-01-30T08:18:31.050 回答
1
private fun sendWhatsappMessage(phoneNumber:String, text:String) {        
  val url = if (Intent().setPackage("com.whatsapp").resolveActivity(packageManager) != null) {
        "whatsapp://send?text=Hello&phone=$phoneNumber"
    } else {
        "https://api.whatsapp.com/send?phone=$phoneNumber&text=$text"
    }

    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    startActivity(browserIntent)
}

这是实现这一目标的更简单的方法。此代码检查设备上是否安装了 whatsapp。如果已安装,它将绕过系统选择器并转到 whatsapp 上的联系人并在聊天中预先输入文本。如果未安装,它会在您的网络浏览器上打开 whatsapp 链接。

于 2019-12-31T06:00:26.323 回答
0

检查此代码,

    public void share(String subject,String text) {
     final Intent intent = new Intent(Intent.ACTION_SEND);

String score=1000;
     intent.setType("text/plain");
     intent.putExtra(Intent.EXTRA_SUBJECT, score);
     intent.putExtra(Intent.EXTRA_TEXT, text);

     startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
于 2013-03-19T10:36:14.627 回答
0

这对我有用:

public static void shareWhatsApp(Activity appActivity, String texto) {

    Intent sendIntent = new Intent(Intent.ACTION_SEND);     
    sendIntent.setType("text/plain");
    sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, texto);

    PackageManager pm = appActivity.getApplicationContext().getPackageManager();
    final List<ResolveInfo> matches = pm.queryIntentActivities(sendIntent, 0);
    boolean temWhatsApp = false;
    for (final ResolveInfo info : matches) {
      if (info.activityInfo.packageName.startsWith("com.whatsapp"))  {
          final ComponentName name = new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name);
          sendIntent.addCategory(Intent.CATEGORY_LAUNCHER);
          sendIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_TASK);
          sendIntent.setComponent(name);
          temWhatsApp = true;
          break;
      }
    }               

    if(temWhatsApp) {
        //abre whatsapp
        appActivity.startActivity(sendIntent);
    } else {
        //alerta - você deve ter o whatsapp instalado
        Toast.makeText(appActivity, appActivity.getString(R.string.share_whatsapp), Toast.LENGTH_SHORT).show();
    }
}
于 2013-12-21T05:28:04.327 回答
0

获取您要发送消息的联系人号码并为whatsapp创建uri,这里c是返回所选联系人的光标。

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);
于 2018-06-16T04:22:19.893 回答
0

文档

要使用将自动出现在聊天文本字段中的预填充消息创建您自己的链接,请使用 https://wa.me/whatsappphonenumber/?text=urlencodedtext其中 whatsappphonenumber 是国际格式和 URL 的完整电话号码-encodedtext 是 URL 编码的预填充消息。

示例:https : //wa.me/15551234567?text=I 'm%20interested%20in%20your%20car%20for%20sale

代码示例

val phoneNumber = "13492838472"
    val text = "Hey, you know... I love StackOverflow :)"
    val uri = Uri.parse("https://wa.me/$phoneNumber/?text=$text")
    val sendIntent = Intent(Intent.ACTION_VIEW, uri)
    startActivity(sendIntent)
于 2020-01-02T17:57:50.530 回答
0

这个终于在 Kotlin 中为我工作了:

private fun navigateToWhatsApp() {
        try {
            val url = "https://api.whatsapp.com/send?phone=+91${getString(R.string.contact)}"
            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).setPackage("com.whatsapp"))
        } catch (e: Exception) {
            showToast("Whatsapp app not installed in your device")
        }
    }
于 2021-04-14T15:54:07.260 回答
-1

如我的文章所示,以下 API 可以在 c++ 中使用。

您需要定义几个常量:

//
#define    GroupAdmin                <YOUR GROUP ADMIN MOBILE PHONE>
#define GroupName                <YOUR GROUP NAME>
#define CLIENT_ID                <YOUR CLIENT ID>
#define CLIENT_SECRET            <YOUR CLIENT SECRET>

#define GROUP_API_SERVER        L"api.whatsmate.net"
#define GROUP_API_PATH          L"/v3/whatsapp/group/text/message/12"
#define IMAGE_SINGLE_API_URL    L"http://api.whatsmate.net/v3/whatsapp/group/image/message/12"

//

然后连接到 API 的端点。

hOpenHandle = InternetOpen(_T("HTTP"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hOpenHandle == NULL)
{
    return false;
}

hConnectHandle = InternetConnect(hOpenHandle,
    GROUP_API_SERVER,
    INTERNET_DEFAULT_HTTP_PORT,
    NULL, NULL, INTERNET_SERVICE_HTTP,
    0, 1);

if (hConnectHandle == NULL)
{
    InternetCloseHandle(hOpenHandle);
    return false;
}

然后发送 header 和 body 并等待需要“OK”的结果。

第 1 步 - 打开一个 HTTP 请求:

const wchar_t *AcceptTypes[] = { _T("application/json"),NULL };
HINTERNET hRequest = HttpOpenRequest(hConnectHandle, _T("POST"), GROUP_API_PATH, NULL, NULL, AcceptTypes, 0, 0);

if (hRequest == NULL)
{
    InternetCloseHandle(hConnectHandle);
    InternetCloseHandle(hOpenHandle);
    return false;
}

第 2 步 - 发送标头:

std::wstring HeaderData;

HeaderData += _T("X-WM-CLIENT-ID: ");
HeaderData += _T(CLIENT_ID);
HeaderData += _T("\r\nX-WM-CLIENT-SECRET: ");
HeaderData += _T(CLIENT_SECRET);
HeaderData += _T("\r\n");
HttpAddRequestHeaders(hRequest, HeaderData.c_str(), HeaderData.size(), NULL);

第 3 步 - 发送消息:

std::wstring WJsonData;
WJsonData += _T("{");
WJsonData += _T("\"group_admin\":\"");
WJsonData += groupAdmin;
WJsonData += _T("\",");
WJsonData += _T("\"group_name\":\"");
WJsonData += groupName;
WJsonData += _T("\",");
WJsonData += _T("\"message\":\"");
WJsonData += message;
WJsonData += _T("\"");
WJsonData += _T("}");

const std::string JsonData(WJsonData.begin(), WJsonData.end());

bResults = HttpSendRequest(hRequest, NULL, 0, (LPVOID)(JsonData.c_str()), JsonData.size());

现在只需检查结果:

TCHAR StatusText[BUFFER_LENGTH] = { 0 };
DWORD StatusTextLen = BUFFER_LENGTH;
HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_TEXT, &StatusText, &StatusTextLen, NULL);
bResults = (StatusTextLen && wcscmp(StatusText, L"OK")==FALSE);
于 2018-11-03T16:39:23.250 回答