我正在实现一个短信应用程序,到目前为止,我已经实现了获取所有消息(发送、接收、草稿)及其联系号码、线程 ID、联系人 ID、日期、类型。
这是我的代码:
Uri mSmsinboxQueryUri = Uri.parse("content://sms");
Cursor cursor = _context.getContentResolver().query(
mSmsinboxQueryUri,
new String[] { "_id", "thread_id", "address", "date", "body",
"type" }, null, null, null);
String[] columns = new String[] { "address", "thread_id", "date",
"body", "type" };
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String address = null, date = null, msg = null, type = null, threadId = null;
address = cursor.getString(cursor.getColumnIndex(columns[0]));
threadId = cursor.getString(cursor.getColumnIndex(columns[1]));
date = cursor.getString(cursor.getColumnIndex(columns[2]));
msg = cursor.getString(cursor.getColumnIndex(columns[3]));
type = cursor.getString(cursor.getColumnIndex(columns[4]));
Log.e("SMS-inbox", "\nTHREAD_ID: "
+ threadId + "\nNUMBER: " + address + "\nTIME: " + date + "\nMESSAGE: " + msg + "\nTYPE: " + type);
}
}
}
现在,我需要按线程 id 分隔这些消息(具有相同线程 id 的消息)。我怎样才能最好地实现这一目标?谢谢!
最佳答案
我一开始就不会单独保存这些字符串。
我要做的是这样的类(class):
public class SmsMsg {
private String address = null;
private String threadId = null;
private String date = null;
private String msg = null;
private String type = null;
//c'tor
public SmsMsg(Cursor cursor) {
this.address = cursor.getString(cursor.getColumnIndex("address"));
this.threadId = cursor.getString(cursor.getColumnIndex("thread_id"));
this.date = cursor.getString(cursor.getColumnIndex("date"));
this.msg = cursor.getString(cursor.getColumnIndex("body"));
this.type = cursor.getString(cursor.getColumnIndex("type"));
}
}
现在您可以在 while 循环中实例化 SmsMsg
对象,只要 cursor.moveToNext()
为 true
并将其添加到您选择的列表
。
您现在可以将所需 threadId
的所有消息复制到不同的 List
并按日期等进行排序。这取决于您想用它做什么。
关于安卓短信: group by its thread id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538798/