今天整理了一下有关ContentObserver相关的代码,注释很详细了,不罗嗦,直接上代码:
package com.ContentProvider;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
public class MainContentProvider extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyContentObserver content = new MyContentObserver(new Handler(), this);
//注册短信变化监听
this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content);
}
}
package com.ContentProvider;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
public class MyContentObserver extends ContentObserver{
private Context mcontext;
public MyContentObserver(Handler handler ,Context context) {
super(handler);
this.mcontext = context;
}
@Override
public void onChange(boolean selfChange) {
// TODO Auto-generated method stub
super.onChange(selfChange);
//读取发件箱中的短信,数据库中是以时间降序来存储短信的,所以,第一条记录就是最新的记录
//如果把 content://sms/outbox 改成 content://sms/inbox,则可以读取收件箱中的短信
Cursor cursor = this.mcontext.getContentResolver().query(Uri.parse("content://sms/outbox"),null, null, null, null);
//如果要读取指定号码的未读短信,则
// Cursor cursor = this.mcontext.getContentResolver().query(Uri.parse("content://sms/inbox"), null,
// " address=? and read=?", new String[]{"123456", "0"}, null);
//其中address为号码,对应 123456;read为已读/未读标志,0为未读,1为已读; body为短信内容
while (cursor.moveToNext()){
StringBuilder sb = new StringBuilder();
//_id为短信编号;address为手机号码;body为短信内容;time为时间,长整型的
sb.append("_id=").append(cursor.getInt(cursor.getColumnIndex("_id")));
sb.append(",address=").append(cursor.getString(cursor.getColumnIndex("address")));
sb.append(";body=").append(cursor.getString(cursor.getColumnIndex("body")));
sb.append(";time=").append(cursor.getLong(cursor.getColumnIndex("date")));
Log.i("ReceiveSendSMS", sb.toString());
}
}
}
记得在AndroidManifest.xml文件中添加权限:
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>