內容觀察者:監聽短信

package com.itheima28.contentobserverdemo;


import android.app.Activity;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;


public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// 監聽系統短信

ContentResolver resolver = getContentResolver();

// 註冊一個內容觀察者觀察短信數據庫
resolver.registerContentObserver(Uri.parse("content://sms/"), true, new MyContentObserver(new Handler()));
}

/**
* @author andong
* 內容觀察者
*/
class MyContentObserver extends ContentObserver {


private static final String TAG = "MyContentObserver";


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


/**
* 當被監聽的內容發生改變時回調
*/
@Override
public void onChange(boolean selfChange) {
Log.i(TAG, "短信改變了");
Uri uri = Uri.parse("content://sms/outbox"); // 發件箱的uri

// 查詢發件箱的內容
Cursor cursor = getContentResolver().query(uri, new String[]{"address", "date", "body"}, null, null, null);
if(cursor != null && cursor.getCount() > 0) {

String address;
long date;
String body;
while(cursor.moveToNext()) {
address = cursor.getString(0);
date = cursor.getLong(1);
body = cursor.getString(2);

Log.i(TAG, "號碼: " + address + ", 日期: " + date + ", 內容: " + body);
}
cursor.close();
}
}
}
}
發佈了34 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章