您好,登錄后才能下訂單哦!
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; } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。