溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

android開(kāi)發(fā)——內(nèi)容觀察者

發(fā)布時(shí)間:2020-07-16 00:07:03 來(lái)源:網(wǎng)絡(luò) 閱讀:436 作者:xiongbuaamao 欄目:移動(dòng)開(kāi)發(fā)

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;
    }
}


向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI