since.2006  

ContentObserver有点类似于BroadcastReceiver,当某类事件发生时进行调用.ContentObserver一般和系统或第三方程序提供的Provider一起使用.

当为某个URI注册了ContentObserver后,对其进行操作后都会调用注册的回调函数,以监视未接电话为例(未读短信和未接电话类似,只需将URI改为短信的URI就可以了):

// 注册ContentObserver
getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, false, new MissedCallContentObserver(this, 

new Handler()));

// 当有call log时,就会对这个类进行回调
public class MissedCallContentObserver extends ContentObserver {
 
 private Context ctx;
 
 private static final String TAG = "MissedCallContentObserver";
 
 public MissedCallContentObserver(Context context, Handler handler) {
  super(handler);
  ctx = context;
 }

 @Override
 public void onChange(boolean selfChange) {
  
  Cursor csr = ctx.getContentResolver().query(Calls.CONTENT_URI, new String[] {Calls.NUMBER, 

Calls.TYPE, Calls.NEW}, null, null, Calls.DEFAULT_SORT_ORDER);
  
  if (csr != null) {
   if (csr.moveToFirst()) {
    int type = csr.getInt(csr.getColumnIndex(Calls.TYPE));
    switch (type) {
    case Calls.MISSED_TYPE:
     Log.v(TAG, "missed type");
     if (csr.getInt(csr.getColumnIndex(Calls.NEW)) == 1) {
      Log.v(TAG, "you have a missed call");
     }
     break;
    case Calls.INCOMING_TYPE:
     Log.v(TAG, "incoming type");
     break;
    case Calls.OUTGOING_TYPE:
     Log.v(TAG, "outgoing type");
     break;
    }
   }
   // release resource
   csr.close();
  }
 }
 
 @Override
 public boolean deliverSelfNotifications() {
  return super.deliverSelfNotifications();
 }
}
Posted by hee at 18:03 PM | Permalink | 评论(2)