这是我处理它的方式(更多在这里):
首先,如果你想确保能够发送消息,可以检查通讯录中的联系人是否有 WhatsApp 账户:
@RequiresPermission(permission.READ_CONTACTS)
public String getContactMimeTypeDataId(@NonNull Context context, String contactId, @NonNull String mimeType) {
if (TextUtils.isEmpty(mimeType) || !PermissionUtil.hasPermissions(context, Manifest.permission.READ_CONTACTS))
return null;
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{Data._ID}, Data.MIMETYPE + "= ? AND "
+ ContactsContract.Data.CONTACT_ID + "= ?", new String[]{mimeType, contactId}, null);
if (cursor == null)
return null;
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
String result = cursor.getString(cursor.getColumnIndex(Data._ID));
cursor.close();
return result;
}
如果一切看起来正常,您可以像从网页打开一样打开它:
final String contactMimeTypeDataId = getContactMimeTypeDataId(context, contactId, "vnd.android.cursor.item/vnd.com.whatsapp.profile");
if (contactMimeTypeDataId != null) {
final String whatsAppPhoneNumber = PhoneNumberHelper.normalizePhone(phoneNumber);
String url = "https://api.whatsapp.com/send?phone="+ whatsAppPhoneNumber ;
intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
.setPackage("com.whatsapp");
startActivity(intent);
}
你还可以在所有这些操作之前检查 WhatsApp 是否已安装(或者移除
setPackage
并检查是否有任何应用程序可以处理 Intent):
final PackageManager packageManager = context.getPackageManager();
final ApplicationInfo applicationInfo = packageManager.getApplicationInfo("com.whatsapp", 0);
if (applicationInfo == null)
return;
编辑:关于使用Uri准备Intent,我认为这种方式更好:
@JvmStatic
fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
val builder = Uri.Builder().scheme("https").authority("api.whatsapp.com").path("send")
normalizedPhoneNumber?.let { builder.appendQueryParameter("phone", it) }
message?.let { builder.appendQueryParameter("text", it) }
return Intent(Intent.ACTION_VIEW, builder.build())
}
或者选择另一种方式(基于此处):
fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
val builder = Uri.Builder().scheme("https").authority("wa.me")
normalizedPhoneNumber?.let { builder.appendPath(it) }
message?.let { builder.appendQueryParameter("text", it) }
return Intent(Intent.ACTION_VIEW, builder.build())
}