内容观察者
内容观察者 resolver.registerContentObserver(uri, true, new MyContentObserver(new Handler())); notifyForDescendents 如果为true,匹配的范围广,只要以uri开头都匹配,false则严格匹配。一般为true |
核心代码: 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;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 当用户点击。就向其注册一个内容观察者,监听短信的数据变化
*
* @param view
*/
public void click(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri.parse("content://sms");
resolver.registerContentObserver(uri, true, new MyContentObserver(
new Handler()));
// notifyForDescendents 如果为true,匹配的范围广,只要以uri开头都匹配,false则严格匹配。一般为true
// new Handler() 什么意思?
}
private class MyContentObserver extends ContentObserver {
private static final String TAG = "MainActivity";
public MyContentObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
// Log.i(TAG, "短信内容变化了。。。");
//将窃听到的短信给获取出来
ContentResolver resolver = MainActivity.this.getContentResolver();
Uri uri = Uri.parse("content://sms");
Cursor cursor = resolver.query(uri, new String[]{"address","body"}, null, null, null);
cursor.moveToFirst();
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndex("body"));
Log.i(TAG, "发件人:" + address);
Log.i(TAG, "内容:"+body);
}
} |
权限: <uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_SMS"/> |