ContentObserver——內(nèi)容觀察者,可以觀察特定uri的數(shù)據(jù)庫的變化,已達(dá)到監(jiān)聽的目的,進(jìn)而對數(shù)據(jù)庫的變化作出相應(yīng)的反應(yīng)。下面是一個(gè)監(jiān)聽短信變化的應(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ù)庫發(fā)生改變時(shí),觸發(fā)此方法
@Override
public void onChange(boolean selfChange) {
System.out.println("您有新短信產(chǎn)生!");
//獲取游標(biāo),對數(shù)據(jù)庫進(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;
}
}另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
分享名稱:android開發(fā)——內(nèi)容觀察者-創(chuàng)新互聯(lián)
網(wǎng)址分享:http://www.chinadenli.net/article44/dcpphe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、定制網(wǎng)站、域名注冊、網(wǎng)頁設(shè)計(jì)公司、網(wǎng)站維護(hù)、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)