初学Android 监控ContentProvider的数据改变 五十七

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

有时候应用中需要监听ContentProvider的改变并提供响应,这时候就要利用ContentObserver类了

不管是ContentProvider中实现的,insert,delete,update方法中的任何一个,程序都会调用getContext().getContentResolver().notifyChange(uri,null);

这行代码可用于通知所有注册在该Uri上的监听者,该ContentProvider所共享的数据发生了改变 

监听ContentProvider数据改变的监听器需要继承ContentObserver类,并重写该基类所定义的onChange(boolean selfChange)方法,当它所监听的ContentProvider所共享的数据发生改变时,该onChange将会触发

为了监听指定的ContentProvider的数据变化,需要通过ContentResolver向指定Uri注册ContentObserver监听器.

用如下方法来注册监听器

registerContentObserver(Uri uri,boolean notifyForDescendents,ContentObserver observer)

notifyForDescendents :如果该参数设为true,假如Uri为content://abc,那么Uri为content://abc/xyz, content://abc/xyz/foo的数据改变时也会触发该监听器,如果参数为false,那么只有                                            content://abc的数据改变时会触发该监听器

下面以监听系统的短信为例,下图为模拟发送一条短信


上面有一条短信内容为hello,下面启动监听程序在logcat中打印该短信的相关信息


下面为代码

package WangLi.IO.MonitorSms;import android.app.Activity;import android.database.ContentObserver;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.os.Handler;public class MonitorSms extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        //为content://sms的数据改变注册监听器        this.getContentResolver().registerContentObserver(Uri.parse("content://sms"), true,           new SmsObserver(new Handler()));    }    //根据自定义的ContentObserver监听类    private final class SmsObserver extends ContentObserver    {  public SmsObserver(Handler handler) {   super(handler);   // TODO Auto-generated constructor stub  }     public void onChange(boolean selfChange)     {      //查询发送箱中的短信(处于正在发送状态的短信放在发送箱)      Cursor cursor = getContentResolver().query(Uri.parse("content://sms/outbox"),         null, null, null, null);      //遍历查询得到结果集,即可获取用户正在发送的短信      while(cursor.moveToNext())      {       StringBuilder sb = new StringBuilder();       //获取短信的发送地址       sb.append("address=").append(         cursor.getString(cursor.getColumnIndex("address")));       //获取短信标题       sb.append(";subject=").append(         cursor.getString(cursor.getColumnIndex("body")));       //获取短信发送时间       sb.append(";time=").append(         cursor.getLong(cursor.getColumnIndex("date")));       System.out.println("Has Sent SMS:::" + sb.toString());      }     }    }}


           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hffyyff/article/details/84195439