---------------------昏割线----------------------
12月07号新增一种方法
-------------------------------------------------
想要读取一个会话的所有信息,千言万语就是要获得thread_id,所以下面增加两种获取thread_id的方法
1.向数据库插入一条空的短信,就可以得到thread_id了
2.关于只想搜彩信的话,改天写
想要获取某一会话的所有短信,你首先得了解android系统存储短信的结构,网上有很多介绍
sms主要结构:
- _id => 短消息序号 如100
- thread_id => 对话的序号 如100
- address => 发件人地址,手机号.如+8613811810000
- person => 发件人,返回一个数字就是联系人列表里的序号,陌生人为null
- date => 日期 long型。如1256539465022
- protocol => 协议 0 SMS_RPOTO, 1 MMS_PROTO
- read => 是否阅读 0未读, 1已读
- status => 状态 -1接收,0 complete, 64 pending, 128 failed
- type => 类型 1是接收到的,2是已发出 (6是等待发送)
- body => 短消息内容
- service_center => 短信服务中心号码编号。如+8613800755500
看到第二项,很明显,想要获取某一会话的所有信息,必须先得到thread_id这个东西才行
那我们就先写一个获取thread_id的函数吧,传入参数是会话中,对方的电话号码
- /**
- * 全局变量
- */
- final String SMS_URI_ALL = "content://sms/";
- final String SMS_URI_INBOX = "content://sms/inbox";
- final String SMS_URI_SEND = "content://sms/sent";
- final String SMS_URI_DRAFT = "content://sms/draft";
- final Uri URI = Uri.parse(SMS_URI_ALL);
- final String ADDRESS = "address";
- final String THREAD_ID = "thread_id";
函数体
- int getThreadId(String number) {
- int threadId=0;
- //根据电话号码去搜索
- ContentResolver cr = context.getContentResolver();
- String[] projection = new String[] { THREAD_ID, ADDRESS };
-
- Cursor cur = cr.query(URI, projection, ADDRESS + " = ?",
- new String[] { number }, null);// asc
-
- int threadIdColumn = cur.getColumnIndex(THREAD_ID);
- if (cur != null) {
-
- while (cur.moveToNext()) {
- //获得会话的thread_id
- threadId = cur.getInt(threadIdColumn);
- Log.v("smsLog", "thread id=" + threadId);
- }
- cur.close();
- }
-
- return threadId;
-
- }
然后是根据该thread_id去搜索所有短信
函数体
- public List<SmsLogList> getSmsInPhone(String number) {
- int thread_id = getThreadId(number);
- sms_list = new ArrayList<SmsLogList>();
- //获得短信_id 号码 人名 短信内容 时间 和 类型
- String[] projection = new String[] { "_id", ADDRESS, "person", "body",
- "date", "type" };
- ContentResolver cr = context.getContentResolver();
- Cursor cur = cr.query(URI, projection, THREAD_ID + " = ?",
- new String[] { Integer.toString(thread_id) }, "date desc");
-
- int nameFieldColumnIndex = cur.getColumnIndex("person");
- int numberFieldColumnIndex = cur.getColumnIndex(ADDRESS);
- int smsbodyColumn = cur.getColumnIndex("body");
- int dateColumn = cur.getColumnIndex("date");
- int typeColumn = cur.getColumnIndex("type");
- if (cur != null) {
-
- while (cur.moveToNext()) {
- SmsLogList smsLogList = new SmsLogList();
- smsLogList.setName(cur.getString(nameFieldColumnIndex));
- smsLogList
- .setPhoneNumber(cur.getString(numberFieldColumnIndex));
- smsLogList.setSmsbody(cur.getString(smsbodyColumn));
- smsLogList.setDate(cur.getLong(dateColumn));
- smsLogList.setType(cur.getString(typeColumn));
- Log.v("smsLog", "setType=" + cur.getString(typeColumn) + " "
- + number);
- sms_list.add(smsLogList);
- }
- cur.close();
- }
- return sms_list;
- }
SmsLogList 是一个类,封装了短信的内容,你们可以自己建一个
返回的list就是该号码的所有会话了