一、代码实现
1.实体类
/**
* 作者:张风捷特烈
* 时间:2018/4/12:16:46
* 邮箱:1981462002@qq.com
* 说明:短信实体类
*/public class SMSBean {
/**
* 短信发送方
*/
public String address; /**
* 号码在通讯录中的姓名:无为null
*/
public String name; /**
* 短信时间
*/
public String date; /**
* 短信内容
*/
public String body; /**
* 1 接收短信 2 发送短信
*/
public int type; /**
* 同一个手机号互发的短信,其序号是相同的
*/
public int thread_id;
@Override public String toString() { return "SMSBean{" + "address='" + address + '\'' + ", name='" + name + '\'' + ", date='" + date + '\'' + ", body='" + body + '\'' + ", type=" + type + ", thread_id=" + thread_id + '}';
}
}2.查询联系人的封装方法
/**
* 获取短信:SMSBean:address发信人 date时间 body信息内容
*
* @param ctx 上下文
* @return 短信bean集合 注意添加读取短信权限
*/
public static List<SMSBean> getSMS(Context ctx) { List<SMSBean> smsBeans = new ArrayList<>(); //[1.]获得ContentResolver对象
ContentResolver resolver = ctx.getContentResolver(); //[2.1]得到Uri :访问raw_contacts的url
Uri uri = Uri.parse("content://sms"); //[3]查询表,获得sms表游标结果集
String[] projection = {"address", "date", "body", "type","person","thread_id"};//访问表的字段
Cursor cursor = resolver.query(
uri, projection, null, null, null); while (cursor.moveToNext()) {//遍历游标,获取数据,储存在bean中
SMSBean smsBean = new SMSBean();
smsBean.address = cursor.getString(0);
smsBean.date = cursor.getString(1);
smsBean.body = cursor.getString(2);
smsBean.type = cursor.getInt(cursor.getColumnIndex("type"));
smsBean.name = cursor.getString(cursor.getColumnIndex("person"));
smsBean.thread_id = cursor.getInt(cursor.getColumnIndex("thread_id"));
smsBeans.add(smsBean);
}
cursor.close(); return smsBeans;
}3.使用:权限:<uses-permission android:name="android.permission.READ_SMS"/>
注意:查询数据库是耗时操作,为了不阻塞主线程,最好新建个线程操作
new Thread(new Runnable() { @Override
public void run() {
List<ContactBean> contact = PhoneUtils_Contact.getContact(MainActivity.this);
System.out.println(contact.get(0));
}
}).start();4.结果

短信.png
作者:张风捷特烈
链接:https://www.jianshu.com/p/4aeca390aacf
随时随地看视频