Android接受验证码自动填入功能(源码+已实现+可用+版本兼容)

实际应用开发中,会经常用到短信验证的功能,这个时候如果再让用户就查看短信.然后再回到界面进行短信的填写,难免有多少有些不方便,作为开发者.本着用户至上的原则我们也应该来实现验证码的自动填写功能,还有一个重要的原因是为了防止恶意注册。今天实现这个功能的方法是用的广播来实现的

首先在AndroidMainfest.xml中加入所需要的权限:

 

<!-- 短信验证登陆功能需要添加次权限来自动填充验证码,用不到可以去掉 -->
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />

 

首先看一下实现的效果,没效果说再多都没用,亲眼看到的才知道适不适合自己

 

 

中效果看完接下来就看怎么实现的了,这里使用的广播为动态注册,因为这个APP在进程杀死之后就不需要监听这个广播了,在Activity的onDestory之后注销广播。

SMSBroadcastReceiver.java

 

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by dingchao on 2018/3/31.
 */

public class SMSBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "SMSBroadcastReceiver";

    private static MessageListener mMessageListener;

    public SMSBroadcastReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Object[] pdus = (Object[]) intent.getExtras().get("pdus");
        for (Object pdu : pdus) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
            String sender = smsMessage.getDisplayOriginatingAddress();
            String content = smsMessage.getMessageBody();
            long date = smsMessage.getTimestampMillis();
            Date timeDate = new Date(date);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(timeDate);

            Log.e(TAG, "onReceive: 短信来自:" + sender);
            Log.e(TAG, "onReceive: 短信内容:" + content);
            Log.e(TAG, "onReceive: 短信时间:" + time);

            if(content.indexOf("优铺")>-1){
                mMessageListener.OnReceived(content);
            }
//            //如果短信号码来自自己的短信网关号码
//            if ("your sender number".equals(sender) && mMessageListener != null) {
//                Log.i(TAG, "onReceive: 回调");
//                mMessageListener.OnReceived(content);
//            }
        }
    }

    // 回调接口
    public interface MessageListener {

        /**
         * 接收到自己的验证码时回调
         *
         * @param message 短信内容
         */
        void OnReceived(String message);
    }

    /**
     * 设置验证码接收监听
     *
     * @param messageListener 自己验证码的接受监听,接收到自己验证码时回调
     */
    public void setOnReceivedMessageListener(MessageListener messageListener) {
        this.mMessageListener = messageListener;
    }
}

 

MainActivity.java

 

import android.Manifest;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

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

import static android.R.attr.phoneNumber;


public class MainActivity extends AppCompatActivity {
    private EditText et_phone, et_code;
    private Button btn_code;
    private static final int REQUEST_PERMISSION_CODE = 0;
    SMSBroadcastReceiver mSMSBroadcastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //实例化IntentFilter对象
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        mSMSBroadcastReceiver = new SMSBroadcastReceiver();
        //注册广播接收
        registerReceiver(mSMSBroadcastReceiver,filter);

        mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
            public void OnReceived(String message) {
                Log.e("tag", "1=" + message);
                et_code.setText(getDynamicPwd(message));//截取6位验证码
            }
        });


        et_phone = (EditText) findViewById(R.id.et_phone);
        et_code = (EditText) findViewById(R.id.et_code);
        btn_code = (Button) findViewById(R.id.btn_code);
        btn_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCode(et_phone.getText().toString());
            }
        });


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, REQUEST_PERMISSION_CODE);
        }

       /* SMSBroadcastReceiver mSMSBroadcastReceiver = new SMSBroadcastReceiver();
        mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
            public void OnReceived(String message) {
                Log.e("tag", "1=" + message);
                et_code.setText(getDynamicPwd(message));//截取6位验证码
            }
        });*/



    }


    /*发送验证码请求*/
    private void getCode(final String phone) {
        Log.e("getCode", "getCode:229:" + phoneNumber);
        RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
        StringRequest strinRequest = new StringRequest(Request.Method.POST, "你的验证码请求接口", new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.e("login", "-------获取到的idjson--------" + s.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("phoneNumber", phone);
                Log.e("map", "map:249:" + phone);
                return map;
            }
        };
        /*设置请求一次*/
        strinRequest.setRetryPolicy(
                new DefaultRetryPolicy(
                        500000,//默认超时时间,应设置一个稍微大点儿的,例如本处的500000
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,//默认最大尝试次数
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
                )
        );
        mQueue.add(strinRequest);/*请求数据*/
    }


    /*高版本手动获取权限*/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length != 0) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "您阻止了app读取您的短信,您可以自己手动输入验证码", Toast.LENGTH_SHORT).show();
                }
            } else {
                Log.e("TAG", "获取权限");

            }
        }
    }


    /**
     * 从字符串中截取连续6位数字组合 ([0-9]{6})截取六位数字 进行前后断言不能出现数字 用于从短信中获取动态密码
     *
     * @param content 短信内容
     * @return 截取得到的6位动态密码
     */
    public String getDynamicPwd(String content) {
        // 此正则表达式验证六位数字的短信验证码
        Pattern pattern = Pattern.compile("(?<![0-9])([0-9]{6})(?![0-9])");
        Matcher matcher = pattern.matcher(content);
        String dynamicPwd = "";
        while (matcher.find()) {
            dynamicPwd = matcher.group();
            Log.i("TAG", "getDynamicPwd: find pwd=" + dynamicPwd);
        }
        return dynamicPwd;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mSMSBroadcastReceiver);
        mSMSBroadcastReceiver = null;
    }
}

 

 

 

主要的步骤代码已经贴出,源码地址链接:https://pan.baidu.com/s/1vbYxHZxw9t0LGF_BkzmpvQ 密码:fxrm

有问题或建议请联系dingchao7323@qq.com

 

posted @ 2018-04-03 11:29  丁先森  阅读(2175)  评论(3编辑  收藏  举报