android获取短信并自动填充

package com.velo.quanquan.util;

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

import net.iaf.framework.util.Loger;
import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.widget.EditText;

/**
 * 读取短信内容 自动填充验证码
 *
 * @author qjx
 *
 */
public class SmsContentUtil extends ContentObserver {

	public static final String SMS_URI_INBOX = "content://sms/inbox";

	private Activity activity = null;

	private String smsContent = "";

	private EditText verifyText = null;

	public SmsContentUtil(Handler handler) {
		super(handler);
	}

	public SmsContentUtil(Activity activity, Handler handler, EditText verifyText) {
		super(handler);
		this.activity = activity;
		this.verifyText = verifyText;
	}

	@Override
	public void onChange(boolean selfChange) {
		super.onChange(selfChange);
		Cursor cursor = null;// 光标
		// 读取收件箱中指定号码的短信
		cursor = activity.getContentResolver().query(Uri.parse(SMS_URI_INBOX), new String[] {
			"_id", "address", "body", "read", "date" }, "address=? and read=?",
			new String[] { "15555215554", "0" }, "date desc");

		if (cursor != null) {// 如果短信为未读模式
			cursor.moveToFirst();
			if (cursor.moveToFirst()) {

				String smsbody = cursor
						.getString(cursor.getColumnIndex("body"));
				Loger.e("smsbody:" + smsbody);
				String regEx = "[^0-9]";
				Pattern p = Pattern.compile(regEx);
				Matcher m = p.matcher(smsbody.toString());
				smsContent = m.replaceAll("").trim().toString();
				verifyText.setText(smsContent);
				verifyText.setSelection(verifyText.getText().toString().trim().length());
			}

		}
	}

}

调用该方法的地方的代码:

SmsContentUtil smsContent = new SmsContentUtil(LoginActivity.this, new Handler(), verifyText);

 // 注册短信变化监听
  this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsContent );

上一篇:专注情感故事短视频,三感video获千万级A+轮融资


下一篇:label标签for属性与表单控件点击选中的联系(单选按钮为例)