温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

内容观察者(一个简单的手机短信窃听器)

发布时间:2020-07-14 01:47:46 来源:网络 阅读:638 作者:秋寒526 栏目:开发技术

一丶内容观察者
  * 在内容提供者中要通知内容发生了变化
         getContext().getContentResolver().notifyChanges(uri,null) ; //null表示没有固定的接收者
  * 在其他应用中写一个观察者,并注册一个实例
         getContentResolver().registerContentObserver(uri,true,Observer) ; //uri观察的主机数据,true表示只要主机匹配即可,Observer表示具体的观察者
示例: 短信窃听器

1.先写一个MyObserver继承ContentObserver,重写onchange方法:
public class MyObserver extends ContentObserver {
    private Context context;
    public MyObserver(Context context, Handler handler) {
        super(handler);
        this.context = context;
    }
    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);

        // 短信表中的字段read : 1代表已经读了,0代表的是未读
        // 短信表中的字段type : 2代表监测的机子发出去的信息,1代表的是监测的机子接收到的信息

        // 拿到内容解析器
        ContentResolver recolver = context.getContentResolver();
        // 查询检测的机子的系统短信
        Cursor cursor = recolver.query(uri, new String[] { "address", "body", "type", "date" },
                null, null, "date desc");
        cursor.moveToFirst() ;
        //拿到短信信息
        String address = cursor.getString(0) ;
        String body = cursor.getString(1) ;
        int type = cursor.getInt(2) ;
        long date = cursor.getLong(3) ;
        
        if(type == 2){
            String d = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(date)) ;
            System.out.println("检测的机子发送了信息: 地址:" + address + " 内容:" + body + "时间 :" + d );
            Toast.makeText(context, "检测的机子发送了信息: 地址:" + address + " 内容:" + body + "时间 :" + d, 0).show() ;
        }
        
        if(type == 1){
            String d = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(date)) ;
            System.out.println("检测的机子接收信息: 地址:" + address + " 内容:" + body + "时间 :" + d );
            Toast.makeText(context, "检测的机子接收了信息: 地址:" + address + " 内容:" + body + "时间 :" + d, 0).show() ;
        }      
    }
}

2.在其他应用中写一个观察者,并注册一个实例

        Uri uri = Uri.parse("content://sms") ;//监测的主机
        getContentResolver().registerContentObserver(uri, true, new MyObserver(this, new Handler())) ;

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI