如何使用特定联系人从其他应用程序打开 Whatsapp?

Akh*_*ank 3 java android chat android-intent whatsapp

我已经阅读了如何从我的应用程序打开 whatsapp,如问题如何从其他应用程序打开 Whatsapp 所述- 但它没有解释如何打开与特定联系人的聊天。有什么办法可以打开与特定联系人的聊天吗?

liv*_*ker 5

You can open whats app with specific contact but that contact must have a whats app account.

private void openWhatsApp() {
    String smsNumber = "91xxxxxxxxxx"; //without '+'
    try {
        Intent sendIntent = new Intent("android.intent.action.MAIN");
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
        sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net");
        sendIntent.setPackage("com.whatsapp");
        startActivity(sendIntent);
    } catch(Exception e) {
        Toast.makeText(this, "Error\n" + e.toString(), Toast.LENGTH_SHORT).show();
    }
}
Run Code Online (Sandbox Code Playgroud)

Common mistakes with above codes are

  1. ACTION_SEND not ACTION_SENDTO
  2. Very careful with contact number, It should have "91" or any other code based on the country.
  3. 不应在数字前使用任何特殊字符,如 +。