效果:
清单:
布局:
代码:
package com.sg31.contentobserver;
import android.support.v7.app.ActionBarActivity;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册内容观察者
registerContentObserver();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void registerContentObserver() {
// 注册一个内容观察者,监听短信数据库内容的改变
ContentResolver cr = getContentResolver();
// uri:监听哪个uri上的内容提供者的通知
// notifyForDescendents:如果是true,那么只要以content://sms开头的uri的数据改变,都能收到通知,比如content://sms/inbox
cr.registerContentObserver(Uri.parse("content://sms"), true,
new SGObserver(new Handler()));
}
class SGObserver extends ContentObserver {
public SGObserver(Handler handler) {
super(handler);
}
// 收到数据改变的通知,此方法调用
@Override
public void onChange(boolean selfChange) {
// TODO Auto-generated method stub
super.onChange(selfChange);
System.out.println("短信数据库改变");
}
}
}