ContentObserver——内容观察者,可以观察特定uri的数据库的变化,已达到监听的目的,进而对数据库的变化作出相应的反应。下面是一个监听短信变化的应用。
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Uri uri = Uri.parse("content://sms/"); getContentResolver().registerContentObserver(uri, true, new SmsObserver(new Handler())); } public class SmsObserver extends ContentObserver{ public SmsObserver(Handler handler) { super(handler); } //当短信数据库发生改变时,触发此方法 @Override public void onChange(boolean selfChange) { System.out.println("您有新短信产生!"); //获取游标,对数据库进行操作 Cursor cursor = getContentResolver().query(Uri.parse("content://sms/outbox"), null, null, null, null); while(cursor.moveToNext()){ StringBuilder sBuilder = new StringBuilder(); sBuilder.append("id=").append(cursor.getInt(cursor.getColumnIndex("_id"))); sBuilder.append(";address=").append(cursor.getString(cursor.getColumnIndex("address"))); sBuilder.append(";body=").append(cursor.getString(cursor.getColumnIndex("body"))); sBuilder.append(";time=").append(cursor.getString(cursor.getColumnIndex("date"))); //Toast.makeText(MainActivity.this, sBuilder.toString(), Toast.LENGTH_LONG).show(); String message = sBuilder.toString(); System.out.println(message); TextView textView = (TextView) MainActivity.this.findViewById(R.id.tv_message); textView.setText("你有短信了\n"+message); } super.onChange(selfChange); } } @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; } }