ContentObserver的基本使用
程序员文章站
2024-02-13 20:42:04
...
ContentObserver的使用类似与设计模式中的观察者模式,ContentObserver是观察者,被观察的ContentProvider是被观察者。当被观察者ContentProvider的数据发生了增删改的变化,就会及时的通知给ContentProvider,ContentObsserver做出相应的处理。
package com.example.android_contentobserver;
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 MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册观察者Observser
this.getContentResolver().registerContentObserver(Uri.parse("content://sms"),true,new SMSObserver(new Handler()));
}
private final class SMSObserver extends ContentObserver {
public SMSObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
Cursor cursor = MainActivity.this.getContentResolver().query(
Uri.parse("content://sms/inbox"), 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("subject")));
sb.append(";body=").append(
cursor.getString(cursor.getColumnIndex("body")));
sb.append(";time=").append(
cursor.getLong(cursor.getColumnIndex("date")));
System.out.println("--------has Receivered SMS::" + sb.toString());
}
}
}
}
转载于:https://my.oschina.net/summerpxy/blog/195269
上一篇: python面试——编码规范