通过ContentResolver监听系统短信变化

需要有读取短信的权限

     <uses-permission android:name="android.permission.READ_SMS"/>

ContentResolver注册一个内容观察者

ContentObserver内容观察者监听系统短信的变化

通过ContentResolver来获取短信内容提供者提供的短信信息

package com.heima.jiantingSms;

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 jiantingSmsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i("jiantingSmsActivity", "短信");
        Log.i("jiantingSmsActivity", "短信");
        //监听系统短信
        ContentResolver resolver = getContentResolver();
        //注册一个内容观察者观察短信数据库
        resolver.registerContentObserver(Uri.parse("content://sms/"), true, new MyContentObserver(new Handler()));
        
       
    }
    
    //内容观察者
    class MyContentObserver extends ContentObserver{

    	private static final String TAG = "MyContentObserver";
		public MyContentObserver(Handler handler) {
			super(handler);
			// TODO Auto-generated constructor stub
		}

		//当被监听的内容发生改变时回调
		@Override
		public void onChange(boolean selfChange) {
			// TODO Auto-generated method stub
			Log.i(TAG, "短信改变了");
			
			Uri uri = Uri.parse("content://sms/outbox");  //发件箱uri
			
			//查看发件箱内容
			ContentResolver resolver = getContentResolver();
			Cursor cursor = resolver.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.getInt(1);
					body = cursor.getString(2);
					Log.i(TAG, "address is " + address + " date is " + date + " body is " + body);
				}
				cursor.close();
			}
			
			
		}
    	
    	
    }
}



你可能感兴趣的:(通过ContentResolver监听系统短信变化)