为了账号安全,请及时绑定邮箱和手机立即绑定

1-AIV--使用ContentProvider获取短信

标签:
Java

一、代码实现

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.结果

webp

短信.png



作者:张风捷特烈
链接:https://www.jianshu.com/p/4aeca390aacf


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
全栈工程师
手记
粉丝
233
获赞与收藏
1008

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消