内容观察者复习监听短信demo
内容观察者,也是需要注册的 注册还是那个小伙子getContentResolver(); 然后得到ContentResolver
registerContentObserver 的第一个属性是 URI 也就是监听这个URI的变化 第二个属性就是URL变化的时候 true 就是通知 我们这里设置为true 第三个 接收回调对象
因为用这个URI 会得到三个变化的数据,所以我们在狙击下 去得到发件箱的URI content://sms/outbox
主要代码就是
package com.example.soundSms; 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 contentResolver = getContentResolver(); contentResolver.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) { 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(); } super.onChange(selfChange); } } }