如何使用WhatsApp从我的应用发送

时间:2019-08-08 20:21:20

标签: android

我已经在手机中安装了WhatsApp,并希望使用以下代码从我的应用中发送WhatsApp消息,但是我正在获取WhatsApp is not installed in your phone?!

        whasappBtn.setOnClickListener {
            val packageManager = it.context.packageManager
            val text = "Hi, we are sending you frm XYZ company."
            val url = "https://api.whatsapp.com/send?phone=$mobile" // &text=$text"
            val whatsAppIntent = Intent().apply {
                setPackage("com.whatsapp")
                action = Intent.ACTION_VIEW
                data = Uri.parse(url)
                type = "text/plain"
                putExtra(Intent.EXTRA_TEXT, text)
            }
            try {
              //  if (whatsAppIntent.resolveActivity(packageManager) != null) {
              //      it.context.startActivity(whatsAppIntent)
              //  }
                startActivity(whatsAppIntent)
              //  startActivity(Intent.createChooser(whatsAppIntent, text));
            } catch (e: Exception) {
                Toast.makeText(this, "WhatsApp is not installed in your phone", Toast.LENGTH_SHORT).show()
                e.printStackTrace()
            }
        }

2 个答案:

答案 0 :(得分:1)

尝试一下:

private void openWhatsApp() {
    String smsNumber = "7****"; // E164 format without '+' sign
    Intent sendIntent = new Intent(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"); //phone number without "+" prefix
    sendIntent.setPackage("com.whatsapp");
    if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
        Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
        return;    
    }
    startActivity(sendIntent);
}

答案 1 :(得分:0)

写相同的已接受答案的另一种方法是:

        whasappBtn.setOnClickListener {
            val sendIntent = Intent("android.intent.action.MAIN").apply {
                setPackage("com.whatsapp")
                type = "text/plain"
                action = Intent.ACTION_SEND
                putExtra("jid", "$mobile@s.whatsapp.net")
                putExtra(Intent.EXTRA_TEXT, "Hi, we are sending you frm XYZ company.")
            }
            try {
                startActivity(sendIntent)
            } catch (e: Exception) {
                Toast.makeText(this, "WhatsApp is not installed in your phone", Toast.LENGTH_SHORT).show()
                e.printStackTrace()
            }
        }