Feb 2024
π Just a little more peachy answer:
Don't forget to add the country code before the number, I mean use the full phone number in international format, without leading zeros, brackets, or dashes. (+1...)
public static void setClickToChat(View v,String toNumber){
String url = "https://api.whatsapp.com/send?phone=" + toNumber;
try {
PackageManager pm = v.getContext().getPackageManager();
pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
v.getContext().startActivity(i);
} catch (PackageManager.NameNotFoundException e) {
v.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
}
Kotlin View extension function :
fun View.openWhatsAppChat(toNumber: String) {
val url = "https://api.whatsapp.com/send?phone=$toNumber"
try {
context.packageManager.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES)
context.startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(url) })
} catch (e: PackageManager.NameNotFoundException) {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))}}
Jetpack Compose :
val toNumber = "+123456789"
val msg = "Hello from Stackoverflow!"
val url = "https://api.whatsapp.com/send?phone=$toNumber"
val context = LocalContext.current
val packageManager = LocalContext.current.packageManager
val intent: Intent = try {
Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, msg)
putExtra(Intent.EXTRA_PHONE_NUMBER, toNumber)
val info = packageManager.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA)
`package` = "com.whatsapp"
}
} catch (e: PackageManager.NameNotFoundException) {
Intent(Intent.ACTION_VIEW, Uri.parse(url))
}
Button(
onClick = {
context.startActivity(intent)
}
) { Text(text = "Open WhatsApp",) }