监听短信数据库,获取验证码

来源:互联网 发布:理财大视野数据靠谱吗 编辑:程序博客网 时间:2024/06/06 04:58

这是我使用比较多的一个工具类,从项目中摘出的,给大家分享。

public class AuthCodeContentObserver extends ContentObserver {public static final String TAG = LogUtil.getLogUtilsTag(AuthCodeContentObserver.class);public static final String SMS_URI = "content://sms/";public static final String SMS_INBOX_URI = "content://sms/inbox";private final Context mContext;private ContentResolver mContentResolver;private Pattern mPattern = Pattern.compile("\\d{4,8}");private OnAuthCodeListener mAuthCodeListener;private String[] mAuthContent;/** * @param handler */public AuthCodeContentObserver(Context context, Handler handler,OnAuthCodeListener l) {super(handler);if (context == null || l == null) {throw new NullPointerException("AuthCodeContentObserver Construction");}mContext = context;mAuthContent = context.getResources().getStringArray(R.array.sms_content);mAuthCodeListener = l;}public void registerAuthCodeContentObserver() {mContext.getContentResolver().registerContentObserver(Uri.parse(SMS_URI), true, this);}public void unregisterAuthCodeContentObserver() {mContext.getContentResolver().unregisterContentObserver(this);}@Overridepublic void onChange(boolean selfChange) {super.onChange(selfChange);Uri inBoxUri = Uri.parse(SMS_INBOX_URI);mContentResolver = mContext.getContentResolver();String[] projection = new String[] { "body", "_id", "date" };String sqlWhere = appendSelection();if (sqlWhere == null || "".equals(sqlWhere)) {return;}Cursor cursor = mContentResolver.query(inBoxUri, projection, sqlWhere,null, null);if (cursor == null || cursor.isClosed()) {return;}try {int position = -1;long receiveTime = 0;while (cursor.moveToNext()) {long date = cursor.getLong(cursor.getColumnIndex(projection[2]));if (date < receiveTime) {continue;}receiveTime = date;position = cursor.getPosition();}if (position >= 0) {cursor.moveToPosition(position);String body = cursor.getString(cursor.getColumnIndex(projection[0]));Matcher matcher = mPattern.matcher(body);boolean find = matcher.find();String splitAuthCode = null;if (find) {splitAuthCode = matcher.group();}mAuthCodeListener.onAuthCode(splitAuthCode);}} catch (Exception e) {LogUtil.e(TAG, e.toString());} finally {if (cursor != null && !cursor.isClosed()) {cursor.close();}}}/** * append sql where selection. *  * @return */public String appendSelection() {StringBuffer selection = new StringBuffer("( ");if (mAuthContent.length - 2 > 0) {for (int i = 0; i < mAuthContent.length - 2; i++) {selection.append("body like \"%" + mAuthContent[i] + "%\" or ");}}if (mAuthContent.length - 1 > 0) {selection.append(" body like \"%" + mAuthContent[0] + "%\" ) ");} else {return null;}selection.append(" and date > "+ (System.currentTimeMillis() - 300000L) + " ");String mSqlWhere = selection.toString();LogUtil.v(TAG, "sql where:" + mSqlWhere);return mSqlWhere;}public interface OnAuthCodeListener {public abstract void onAuthCode(String authCode);}}
R.array.sms_content
<?xml version="1.0" encoding="utf-8"?><resources>    <string-array name="sms_content">        <item>10086</item>        <item>10010</item>    </string-array>
<pre name="code" class="html"></resources>

使用:

1.注册:

// 注册监听短信消息        mContentObserver = new AuthCodeContentObserver(this, new Handler(),                new AuthCodeContentObserver.OnAuthCodeListener() {@Overridepublic void onAuthCode(String authCode) {mAuthSmsCode = authCode;        mAuthcodeText.setText(mAuthSmsCode);        mAuthcodeText.setSelection(mAuthcodeText.getText().toString().length());}});        getContentResolver().registerContentObserver(                Uri.parse("content://sms/"), true, mContentObserver);
2.注销:

if (mContentObserver != null) {            getContentResolver().unregisterContentObserver(mContentObserver);            mContentObserver = null;        }
需要权限:
<pre name="code" class="html"><uses-permission android:name="android.permission.SEND_SMS" /><uses-permission android:name="android.permission.READ_SMS" />
代码都是摘过来的。。嘿嘿



0 0