如何以编程方式使用whatsapp将消息发送到号码

时间:2020-04-14 12:30:52

标签: android android-studio

默认情况下,当用户单击按钮时,我尝试使用电话号码(电话)打开聊天。 但它根本没有开始。

case R.id.nav_chat:             
       PackageManager packageManager = getApplicationContext().getPackageManager();
       Intent whatsapp_intent = new Intent(android.content.Intent.ACTION_SEND);

       try {
             String phone = "123456789";
             String message = "Hello, can you help with my issues?";
             String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
             whatsapp_intent.setPackage("com.whatsapp");
             whatsapp_intent.setData(Uri.parse(url));
             if (whatsapp_intent.resolveActivity(packageManager) != null) {
                 getApplication().startActivity(whatsapp_intent);
             }
        } catch (Exception e){
               e.printStackTrace();
        }
        break;
}

这个问题的答案最初出现在这里 https://stackoverflow.com/a/45821831/12632081

1 个答案:

答案 0 :(得分:0)

您应该将Intent操作设置为ACTION_VIEW而不是ACTION_SEND

Intent whatsapp_intent = new Intent(android.content.Intent.ACTION_VIEW);

此外,您应该使用本地Context而不是应用程序context

//get it from your activity as `this` or from your fragment as: getActivity().getContext()
context.startActivity(whatsapp_intent);