您好,登錄后才能下訂單哦!
ContentObserver——內(nèi)容觀察者,可以觀察特定uri的數(shù)據(jù)庫(kù)的變化,已達(dá)到監(jiān)聽(tīng)的目的,進(jìn)而對(duì)數(shù)據(jù)庫(kù)的變化作出相應(yīng)的反應(yīng)。下面是一個(gè)監(jiān)聽(tīng)短信變化的應(yīng)用。
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); } //當(dāng)短信數(shù)據(jù)庫(kù)發(fā)生改變時(shí),觸發(fā)此方法 @Override public void onChange(boolean selfChange) { System.out.println("您有新短信產(chǎn)生!"); //獲取游標(biāo),對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作 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; } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。