通过 WhatsApp 发送信息

因为我发现了一些旧的帖子,告诉我 whatsapp 不支持这个,我想知道是否有什么改变了,是否有一种方法可以打开 whatsapp 的“聊天”与一个数字,我正在通过一个意图发送?

313322 次浏览

检查这个代码,

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

更新 请参考 < a href = “ https://faq.whatsapp.com/en/android/26000030/? type = 5245251”rel = “ noReferrer”> 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

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

与这里和其他论坛的一些其他线程的报告相匹配,我找到的登录名是: 国际区号,开头没有0或 + ,+ 电话号码,开头没有0 +@s. whatsapp.net

例如,如果你住在荷兰,你的电话号码是0612325032,那么你的电话号码是31612325023@s. whatsapp.net-> + 31(荷兰) ,没有0或 + ,电话号码没有0。

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


}

这对我有用:

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

使用这个代码,您可以用给定的数字打开 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, ""));
}

这对我有用:

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.");
}

无论是否安装 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;
}

这个过程很漫长,但很有效。 享受你的代码:)

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


}

下面的代码是由 GoogleNow 应用程序使用,将不会为任何其他应用程序工作。

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

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

最近 WhatsApp 专门为 Google Now 添加了一个意图,看起来应该是这样的:

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”是一个 PendingInant 它包含一个 IBinder-Object,该对象被发送回 Google App 并检查它是否由 Google Now 创建。

否则 WhatsApp 将不接受该消息。

我在这里真的迟到了,但我相信现在我们有更短和更好的解决方案,通过 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 常见问题解答

棉花糖 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 没有安装这将 抛出异常,如果电话号码不知道,他们将提供通过短信或简单的短信发送邀请

简单的解决办法,试试这个。

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

目前,你可以向 唯一的官方空气污染指数提出以下 GET请求:

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

无论如何,有一个 已经由 WhatsApp 运行的机密 API 程序

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

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

正如 文件所说,你只需要使用如下 URL:

https://wa.me/15551234567

E164格式中最后一段的数字在哪里

Uri uri = Uri.parse("https://wa.me/15551234567");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

下面的 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;
}

然后发送头和正文,等待需要“ 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);

第三步-发送信息:

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

使用此单行代码通过 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
}

这就是对我有效的方法:

        Uri uri = Uri.parse("https://api.whatsapp.com/send?phone=" + "<number>" + "&text=" + "Hello WhatsApp!!");
Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(sendIntent);
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 链接。

来自 文件

使用预填充的消息创建自己的链接 自动出现在聊天的文本字段中,使用 Https://wa.me/whatsappphonenumber/?text=urlencodedtext What sappphonennumber 是一个国际格式的完整电话号码 URL 编码的文本是 URL 编码的预填充消息。

例如: https://wa.me/15551234567?text=I m% 20interest% 20in% 20your% 20car% 20for% 20sales

代码示例

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)

使用 whatsapp 的直接 URL

String url = "https://api.whatsapp.com/send?phone="+number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

您需要使用以下格式的 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

检查设备中是否安装了 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()
}

Java:

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

如果没有安装 WhatsApp,getPackageInfo()将抛出 NameNotFoundException

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

参考文献:

在 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")
}
}

这是通过 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>

有关详细信息,请参阅此 回答

发送到联系人列表中存在 < strong > 的 WhatsApp 号码。 注意,我们使用的是 < strong > ACTION _ SEND

 Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, "SMS TEXT, TEXT THAT YOU NEED TO SEND");
try {
startActivityForResult(whatsappIntent, 100);
} catch (Exception e) {
Toast.makeText(YourActivity.this, "App is not installed", Toast.LENGTH_SHORT).show();
}

如果号码 联系人名单里没有.使用 WhatsApp API

 String number = number_phone.getText().toString(); // I toke it from Dialog box
number = number.substring(1); // To remove 0 at the begging of number (Optional) but needed in my case
number = "962" + number; // Replace it with your country code
String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + Uri.parse("Text that you want to send to the current user");
Intent whatsappIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(YourActivity.this, "App is not installed", Toast.LENGTH_SHORT).show();
}