package com.example.smswatcher; import com.pas.model.SmsInfo; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.content.ContentResolver; import android.database.ContentObserver; import android.database.Cursor; import android.text.Layout; import android.view.Menu; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { LinearLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout=(LinearLayout)findViewById(R.id.ll); ContentResolver resolver = getContentResolver(); Uri uri = Uri.parse("content://sms/"); //註冊觀察者 resolver.registerContentObserver(uri, true, new MyObserver(new Handler())); } private class MyObserver extends ContentObserver { public MyObserver(Handler handler) { super(handler); } // 內容觀察者觀察到內容變化調用 // 觀察到消息郵箱有一條數據庫內容變化的通知 @Override public void onChange(boolean selfChange) { super.onChange(selfChange); SmsInfo sms=getLastSms(); TextView tv=new TextView(MainActivity.this); tv.setText(sms.toString()); // Toast.makeText(MainActivity.this, sms.toString(), Toast.LENGTH_LONG).show(); layout.addView(tv); } } @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; } private SmsInfo getLastSms() { 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(0); String date = cursor.getString(1); String type = cursor.getString(2); String body = cursor.getString(3); cursor.close(); return new SmsInfo(address, type, date, body); } }
若是想在自定義的邏輯裏面添加通知,使用: java
context.getContentResolver() .notifyChange(Uri.parse("content://com.pas.sqlite.personprovider"), null);