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