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

2023-05-09,,

一丶内容观察者
  * 在内容提供者中要通知内容发生了变化
         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())) ;

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

下载本文的Word格式文档,以方便收藏与打印。