監聽短信數據庫的變化,標記爲read_already

 

package ying.android;

import android.app.Activity;
import android.content.ContentValues;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;

public class ScreenTest extends Activity {
 class SmsContent extends ContentObserver {
  private Cursor cursor = null;

  public SmsContent(Handler handler) {
   super(handler);
  }

  /**
   * @Description 當短信表發送改變時,調用該方法 需要兩種權限 android.permission.READ_SMS 讀取短信
   *              android.permission.WRITE_SMS 寫短信
   */
  @Override
  public void onChange(boolean selfChange) {
   // TODO Auto-generated method stub
   super.onChange(selfChange);
   // 讀取收件箱中指定號碼的短信
   cursor = managedQuery(Uri.parse("content://sms/inbox"),
     new String[] { "_id", "address", "read" },
     " address=? and read=?",
     new String[] { "12345678901", "0" }, "date desc");
   if (cursor != null) {
    ContentValues values = new ContentValues();
    values.put("read", "1"); // 修改短信爲已讀模式
    cursor.moveToFirst();
    while (cursor.isLast()) {
     // 更新當前未讀短信狀態爲已讀
     getContentResolver().update(
       Uri.parse("content://sms/inbox"), values, " _id=?",
       new String[] { "" + cursor.getInt(0) });
     cursor.moveToNext();
    }
   }
  }
 }

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  SmsContent content = new SmsContent(new Handler());
  // 註冊短信變化監聽
  this.getContentResolver().registerContentObserver(
    Uri.parse("content://sms/"), true, content);
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章