一张图了解内容观察者:
背景
通过发送一条短信,然后手机接收到,那么数据库必然改变,内容观察者这时候就起作用了。
程序
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ContentResolver resolver = getContentResolver(); Uri uri = Uri.parse("content://sms/"); //注册 resolver.registerContentObserver(uri, true, new MyObserver(new Handler())); } class MyObserver extends ContentObserver { public MyObserver(Handler handler) { super(handler); } //当内容观察者观察到数据库的内容发生了变化就会调用这个方法 //观察到消息邮箱里有一条数据库内容变化的通知 @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Toast.makeText(MainActivity.this, "数据库的内容发生了变化", Toast.LENGTH_LONG).show(); Uri uri = Uri.parse("content://sms/"); ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(uri, new String[]{"address" ,"date", "type", "body"}, null, null, null); cursor.moveToFirst(); String address = cursor.getString(cursor.getColumnIndex("address")); String body = cursor.getString(cursor.getColumnIndex("body")); System.out.println("address"+address+"+++++++body:"+body); cursor.close(); } } }
效果
注意一下短信的读取的权限哈!!
我是天王盖地虎的分割线
源代码:http://pan.baidu.com/s/1dD1Qx01
内容观察者.zip
转载请注明出处:http://www.cnblogs.com/yydcdut