public class MainActivity extends Activity {
private
SmsInfoBean
smsBean
;
private
TextView
tv
;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main
);
tv
=( TextView) findViewById(R.id.
tv
);
//获取内容解析者
ContentResolver resolver = getContentResolver();
//调用内容观察者: 1.关心的数据的路径 2.路径条件满足时 3.内容观察者(观察数据:改变时告诉你)
resolver.registerContentObserver(Uri. parse(
"content://sms/"
),
true
,
new
Myobserver(
new
Handler()));
}
/**
* 创建内容观察者
*
@author
Administrator
*
*/
private
class
Myobserver
extends
ContentObserver{
public
Myobserver(Handler handler) {
super
(handler);
}
/**
* 内容观察者观察数据变化时调用
*/
@Override
public
void
onChange(
boolean
selfChange) {
super
.onChange(selfChange);
//读取短信记录
Cursor cursor = getContentResolver().query(Uri.parse(
"content://sms/"
),
new
String[]{
"address"
,
"body"
,
"date"
},
null
,
null
,
null
);
cursor.moveToFirst();
String address = cursor.getString(cursor.getColumnIndex(
"address"
));
String body = cursor.getString(cursor.getColumnIndex(
"body"
));
String date = cursor.getString(cursor.getColumnIndex(
"date"
));
smsBean
=
new
SmsInfoBean();
smsBean
.setAddress(address);
smsBean
.setBody(body);
smsBean
.setDate(date);
tv
.setText(
smsBean
.toString());
}
}
}
--------------------------------------------------------------------------------------------------
// 注册ContentObserver监听ContentProvider中的数据修改, 当数据被修改的时候, 重新查询数据库, 刷新界面
getContentResolver().registerContentObserver(Uri. parse(
"content://ItheimaProvider"
),
true
,
new
MyObserver());
}
private
class
MyObserver
extends
ContentObserver {
public
MyObserver() {
super
(
new
Handler());
// 处理器, 用来做线程之间的通信
}
public
void
onChange(
boolean
selfChange) {
// 当收到数据修改通知时, 调用这里
list
=
dao
.queryAll();
adapter
.notifyDataSetChanged();
}
}