Android 意图从代码调用 Whatsapp



我正在使用此代码直接从我的通话记录应用程序调用WhatsApp。这很有效,但前提是电话号码包含有效的国家/地区代码。例如,用919789006685调用WhatsApp是有效的,但用97890 06685调用它不起作用。这里的 91 是国家代码。

由于我的应用程序从通话记录中读取电话号码,因此无论存储的电话号码格式如何,我都应该能够使用任何有效的联系电话号码调用 WhatsApp。用户可能在其联系人中存储不包含国家/地区代码的号码。那么这个问题有解决方法吗?

我的应用中使用的代码:

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
String waNumber = contactPhone.replace("+", "");
sendIntent.putExtra("jid", waNumber + "@s.whatsapp.net");
startActivity(sendIntent);

这是完整的解决方案。对于从其应用程序中尝试相同操作的用户可能很有用。感谢Sourav Ganguly的链接。

安卓制造WhatsApp呼叫

  1. 检索所选联系人的 ID。
  2. 从 ContactsContract 获取联系人 ID 的所有 RAW 联系人 ID。
  3. 在 ContactsContract.Data 表中查询所有原始联系人,并检索列ContactsContract.Data._ID
  4. 由于联系人可能在WhatsApp上有多个活动电话号码,因此您可能需要另外检查ContactsContract.Data.DATA3列以过滤出要匹配的电话号码
  5. 要开始WhatsApp对话,请使用vnd.android.cursor.item/vnd.com.whatsapp.profile和vnd.android.cursor.item/vnd.com.whatsapp.voip.call,如果你想开始WhatsApp通话,请使用vnd.android.cursor.item/vnd.whatsapp.voip.call。
  6. 使用第 3 步中的 ID 启动 WhatsApp。下面是示例代码:

    String data = "content://com.android.contacts/data/" + dataId;
    String type = "vnd.android.cursor.item/vnd.com.whatsapp.profile";
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_VIEW);
    sendIntent.setDataAndType(Uri.parse(data), type);
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent);
    

WhatsApp 用于特定电话号码

val whatsAppIntent = Intent(Intent.ACTION_VIEW)
val encodedText = URLEncoder.encode("Helo World", "UTF-8")
whatsAppIntent.data = Uri.parse("http://api.whatsapp.com/send?phone=$phoneNumber&text=$encodedText")
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.setPackage("com.whatsapp");
sharingIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml("<p>https://play.google.com/store/apps/details?id=" + context.getPackageName() + "</p>"));
context.startActivity(Intent.createChooser(sharingIntent, "Share using"));

最新更新