短信监听,自动获短信取验证码

随着Android版本的不断更新,在4.0以上使用广播接收器已经监听不到短信了

还是使用ContentObserver来监听


SmsContentObserver:

package observer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.CursorLoader;
import android.util.Log;

public class SmsContentObserver extends ContentObserver {
	
	/**收到短信时Message的what值*/
	public static final int MESSAGE_WHAT_SMS_RECEIVED = 0x01;
	/**SMS收件箱的URI*/
	public static final String SMS_URI_INBOX = "content://sms/inbox";
	private Context context = null;
	private Handler handler;
	

	public SmsContentObserver(Context context, Handler handler) {
		super(handler);
		this.context = context;
		this.handler = handler;
	}

	@Override
	public void onChange(boolean selfChange) {
		super.onChange(selfChange);
		Cursor cursor = null;// 光标
		// 读取收件箱中指定号码的短信
		// cursor = context.managedQuery(Uri.parse(SMS_URI_INBOX), new String[]
		// {
		// "_id", "address", "body", "read" }, "address=? and read=?",
		// new String[] { "10086", "0" }, "date desc");
		
		//read=0 未读短信
		CursorLoader loader = new CursorLoader(context,Uri.parse(SMS_URI_INBOX), new String[] {
			"_id", "address", "body", "read" }, "read=?",
			new String[]{"0"}, "date desc");
		cursor = loader.loadInBackground();
		if (cursor != null) {// 如果短信为未读模式
			cursor.moveToFirst();
			if (cursor.moveToFirst()) {
				String smsbody = cursor
						.getString(cursor.getColumnIndex("body"));
				Log.i("info","短信内容:" + smsbody);
				
				String regEx = "[^0-9]";
				Pattern p = Pattern.compile(regEx);
				Matcher m = p.matcher(smsbody.toString());
				String smsContent = m.replaceAll("").trim().toString();
				Message msg = Message.obtain();
				msg.obj = smsContent;
				msg.what = MESSAGE_WHAT_SMS_RECEIVED;
				handler.sendMessage(msg);
				
			}
		}
	}
}

使用方法-在需要的地方添加如下代码:

Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case SmsContentObserver.MESSAGE_WHAT_SMS_RECEIVED:
					String smsContent = msg.obj.toString();
					textView.setText(smsContent);
					break;

				default:
					break;
				}
			}
		};
		SmsContentObserver content = new SmsContentObserver(this, handler);
		// 注册短信变化监听
		this.getContentResolver().registerContentObserver(
				Uri.parse(SmsContentObserver.SMS_URI_INBOX), true, content);




你可能感兴趣的:(Android)