You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

检测联系人手机号是否开通WhatsApp及实现预填内容跳转

检测通讯录手机号是否开通WhatsApp

Android 实现

  • 利用WhatsApp内置的Content Provider直接查询号码注册状态:

    private boolean isWhatsAppRegistered(Context context, String phoneNumber) {
        // 格式化手机号:移除所有非数字字符,保留国家码+纯号码
        String formattedNumber = phoneNumber.replaceAll("[^0-9]", "");
        Uri whatsappStatusUri = Uri.parse("content://com.whatsapp.provider.status");
        Cursor cursor = context.getContentResolver().query(
            whatsappStatusUri,
            null,
            "jid LIKE ?",
            new String[]{formattedNumber + "@s.whatsapp.net"},
            null
        );
        boolean exists = (cursor != null && cursor.getCount() > 0);
        cursor?.close();
        return exists;
    }
    

    权限配置:在AndroidManifest.xml中添加

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
    

    注意:该方法依赖WhatsApp内部Provider结构,后续版本可能变更,需做好兼容降级。

  • 备选方案:通过Intent尝试唤起对应号码的聊天窗口,若无法唤起则说明号码未注册或WhatsApp未安装,但无法区分两种情况。

iOS 实现

  • 通过Universal Links判断号码是否可被WhatsApp识别:
    func isWhatsAppRegistered(for phoneNumber: String) -> Bool {
        let formattedNumber = phoneNumber.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
        guard let url = URL(string: "https://api.whatsapp.com/send?phone=\(formattedNumber)") else { return false }
        return UIApplication.shared.canOpenURL(url)
    }
    
    配置要求:在Info.plist中添加
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>whatsapp</string>
    </array>
    
    说明:该方法仅能判断号码是否符合WhatsApp的识别规则,无法100%精准确认注册状态,但这是iOS平台下相对可靠的方案。

实现WhatsApp预设消息+图片分享(类似Cred效果)

Android 实现

  • 使用Intent.ACTION_SEND同时传递文本和图片Uri,WhatsApp会自动填充内容:
    private void shareToWhatsApp(Context context, String phoneNumber, String message, Uri imageUri) {
        String formattedNumber = phoneNumber.replaceAll("[^0-9]", "");
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.setPackage("com.whatsapp");
        
        // 填充预设消息
        shareIntent.putExtra(Intent.EXTRA_TEXT, message);
        // 传入图片Uri(必须用FileProvider生成,避免权限问题)
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        // 指定目标联系人
        shareIntent.putExtra("jid", formattedNumber + "@s.whatsapp.net");
        
        if (shareIntent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(shareIntent);
        }
    }
    
    关键注意点:
    • 图片Uri需通过FileProvider生成,示例配置:
      <provider
          android:name="androidx.core.content.FileProvider"
          android:authorities="${applicationId}.fileprovider"
          android:exported="false"
          android:grantUriPermissions="true">
          <meta-data
              android:name="android.support.FILE_PROVIDER_PATHS"
              android:resource="@xml/file_paths" />
      </provider>
      
    • 确保目标设备上的WhatsApp版本支持同时接收文本和图片,旧版本可能仅支持单一类型。

iOS 实现

  • 使用UIActivityViewController实现文本+图片的分享(iOS通过URL Scheme无法预填图片,此为唯一可行方案):
    func shareToWhatsApp(phoneNumber: String, message: String, image: UIImage) {
        let formattedNumber = phoneNumber.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
        // 将图片写入临时目录
        guard let imageData = image.jpegData(compressionQuality: 0.8),
              let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent("share_img.jpg") else { return }
        do {
            try imageData.write(to: tempFileURL)
            let shareItems: [Any] = [message, tempFileURL]
            let activityVC = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
            // 过滤仅显示WhatsApp
            activityVC.excludedActivityTypes = [.airDrop, .message, .mail, .print, .copyToPasteboard]
            // 弹出分享界面
            if let topVC = UIApplication.shared.keyWindow?.rootViewController {
                topVC.present(activityVC, animated: true)
            }
        } catch {
            print("图片保存失败:\(error.localizedDescription)")
        }
    }
    
    若仅需预填文本,可直接使用URL Scheme:
    func openWhatsAppWithText(phoneNumber: String, message: String) {
        let formattedNumber = phoneNumber.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
        guard let encodedText = message.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
              let url = URL(string: "whatsapp://send?phone=\(formattedNumber)&text=\(encodedText)") else { return }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }
    

内容的提问来源于stack exchange,提问作者Kaviarasan Sandirasekaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:27:06