android 自动获取短信验证码



 

很多项目中都会用到,自动获取验证码填到输入框,这样用户体验比较好,废话不多说,现在实现

 

 

用的是ContentObserver这个类,帮助我们来监听短信数据库发生的变化

package com.smart.android.activity;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.EditText;

import com.smart.android.R;
import com.smart.android.base.BaseActivity;
import com.smart.android.utils.SmsObserver;

/**
 * @Title:
 * @Description:
 * @Author:leo
 * @Since:
 * @Version:
 */

public class ObtainMsgActivity extends BaseActivity {


    public static final int MSG_RECEIVED_CODE = 1;
    private EditText mEditText;
    private SmsObserver mObserver;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == MSG_RECEIVED_CODE)
            {
                String code = (String)msg.obj;
                mEditText.setText(code);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_obtainmsg);
        mEditText = (EditText)findViewById(R.id.et_msg);
        mObserver = new SmsObserver(ObtainMsgActivity.this, mHandler);
        Uri uri = Uri.parse("content://sms");
        getContentResolver().registerContentObserver(uri, true, mObserver);

    }
}
package com.smart.android.utils;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;

import com.smart.android.activity.ObtainMsgActivity;

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

/**
 * @Title:
 * @Description:
 * @Author:leo
 * @Since:
 * @Version:
 */

public class SmsObserver extends ContentObserver {

    private Handler mHandler;
    private Context mContext;
    public SmsObserver(Context context,Handler handler) {
        super(handler);
        mContext = context;
        mHandler = handler;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);
        String code;
        if (uri.toString().equals("content://sms/raw"))  ////onChange会执行二次,第二次短信才会入库
        {
            return ;
        }

        Uri inboxUri = Uri.parse("content://sms/inbox");
        Cursor c = mContext.getContentResolver().query(inboxUri, null, null, null, "date desc");
        if (c != null) {
            if (c.moveToFirst()) {
                String body = c.getString(c.getColumnIndex("body"));//获取短信内容
                Pattern pattern = Pattern.compile("(\\d{6})");//正则表达式   连续6位数字
                Matcher matcher = pattern.matcher(body);

                if (matcher.find()) {
                    code = matcher.group(0);
                    mHandler.obtainMessage(ObtainMsgActivity.MSG_RECEIVED_CODE, code).sendToTarget();
                }
            }
            c.close();
        }
    }
}



你可能感兴趣的:(android)