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

如何在Android中获取特定号码的完整短信对话(含已发送短信)

问题:如何获取特定号码的完整短信对话?

我现在有一段Android代码可以获取指定号码的收件箱短信,但不知道怎么同时获取已发送短信并整合出完整的对话记录,现有代码如下:

private void showContacts(String number) { 
    ArrayList<Bean_Chat> arrayList=new ArrayList(); 
    String[] phoneNumber = new String[] { number }; 
    ContentResolver contentResolver =getContentResolver(); 
    Cursor smsInboxCursor = contentResolver.query((Uri.parse("content://sms/inbox")), new String[]{}, "address=?", phoneNumber, null); 
    int indexBody = smsInboxCursor.getColumnIndex("body"); 
    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return; 
    adapter=null; 
    do { 
        String inbox= smsInboxCursor.getString(indexBody) + "\n"; 
        arrayList.add(new Bean_Chat("",inbox)); 
    } while (smsInboxCursor.moveToNext()); 
}

解决方案:获取完整对话(收件箱+已发送)

要拿到完整的对话记录,我们需要同时查询收件箱和已发送箱的短信,并且按时间戳排序,这样对话才会是正确的时间顺序。另外,最好区分每条短信是“收到”还是“发送”的,方便UI展示。

关键调整点:

  1. 扩展查询范围:用content://sms/作为基础Uri,通过type字段筛选收件(type=1)和已发(type=2)短信
  2. 补充必要字段:除了短信内容body,还要获取date(时间戳,用于排序)和type(区分收发)
  3. 按时间排序:查询时指定date ASC,确保对话按时间先后排列
  4. 权限提醒:Android 6.0及以上需要动态申请READ_SMS权限

修改后的完整代码:

private void showFullConversation(String number) {
    ArrayList<Bean_Chat> chatList = new ArrayList<>();
    String[] selectionArgs = new String[]{number};
    ContentResolver contentResolver = getContentResolver();

    // 同时查询收件箱和已发送箱,按时间升序排序
    String selection = "address=? AND (type=1 OR type=2)";
    Cursor smsCursor = contentResolver.query(
            Uri.parse("content://sms/"),
            new String[]{"body", "date", "type"}, // 需要的核心字段
            selection,
            selectionArgs,
            "date ASC" // 按时间顺序排列对话
    );

    if (smsCursor == null || smsCursor.getCount() == 0) {
        return;
    }

    // 获取各字段的索引,避免重复查询提升性能
    int bodyIndex = smsCursor.getColumnIndex("body");
    int typeIndex = smsCursor.getColumnIndex("type");

    if (bodyIndex < 0 || typeIndex < 0) {
        smsCursor.close();
        return;
    }

    // 遍历Cursor,将短信按类型加入列表
    while (smsCursor.moveToNext()) {
        String messageBody = smsCursor.getString(bodyIndex);
        int messageType = smsCursor.getInt(typeIndex);
        // 根据type判断是发送还是收到的消息(type=2为已发送)
        boolean isSentMessage = messageType == 2;
        // 假设Bean_Chat支持区分收发的构造函数,比如Bean_Chat(isSent, content)
        chatList.add(new Bean_Chat(isSentMessage, messageBody));
    }

    smsCursor.close(); // 务必关闭Cursor,避免内存泄漏

    // 这里可以更新Adapter展示完整对话
    // adapter = new ChatAdapter(chatList);
    // recyclerView.setAdapter(adapter);
}

额外提示:

  • 建议给Bean_Chat添加一个布尔字段(比如isSent),这样UI上可以区分发送/接收消息的布局(比如左对齐/右对齐)
  • 注意号码格式兼容:有些短信的address字段可能带区号、空格或特殊符号,查询前可以统一格式化号码(比如去掉非数字字符)
  • Android 10+系统对短信权限限制更严格,如果是面向高版本系统,需确保权限申请流程合规

内容的提问来源于stack exchange,提问作者Bj Creative

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:03:19