获取短信验证码自动填写并验证
bbpg6219
9年前
来自: http://my.oschina.net/u/2600948/blog/607002
@SuppressLint({"ShowToast", "HandlerLeak"}) public class RecordActy extends Activity implements OnClickListener { private Button getCodebtn; //获取验证码 private EditText codeET; //验证码输入框 private EditText phoneET; //电话号码 private Button submitbtn; //提交按钮 private ImageView backIV; //返回按钮 private Context context; private int i = 60; //倒计时数 private boolean flag = true; private SmsContent content; /* * 处理验证码信息 */ private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == -1) { getCodebtn.setText(i + "秒"); } else if (msg.what == -2) { getCodebtn.setText("验证码"); getCodebtn.setClickable(true); } else { int event = msg.arg1; int result = msg.arg2; Object data = msg.obj; if (result == SMSSDK.RESULT_COMPLETE) { if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) { new Thread(new Runnable() { @Override public void run() { phoneNum = phoneET.getText().toString(); finish(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { Toast.makeText(getApplicationContext(), "验证码已经发送", Toast.LENGTH_SHORT).show(); } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {// 返回支持发送验证码的国家列表 Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show(); } } else { if (flag) { Toast.makeText(getApplicationContext(), "验证错误", Toast.LENGTH_SHORT).show(); } else { ((Throwable) data).printStackTrace(); } } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acty_submit); SwipeBackLayout mSwipeBackLayout = getSwipeBackLayout(); mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT); // 初始化界面 initView(); // 初始化短信验证SDK initSMS(); // initObserver(); } private void initObserver() { content = new SmsContent(new Handler()); // 注册短信监听变化 this.getContentResolver().registerContentObserver( Uri.parse("content://sms/"), true, content); } private void initView() { context = this; findViews(); setSpnAdapter(); setListener(); } private void setListener() { getCodebtn.setOnClickListener(this); submitbtn.setOnClickListener(this); } private void findViews() { getCodebtn = (Button) findViewById(R.id.as_btn_getCode); codeET = (EditText) findViewById(R.id.as_et_code); phoneET = (EditText) findViewById(R.id.as_et_phoneNum); submitbtn = (Button) findViewById(R.id.as_btn_submit); phoneET.setOnTouchListener(new OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { phoneET.setFocusable(false); } return false; } }); } private void initSMS() { // 启动短信验证sdk SMSSDK.initSDK(RecordActy.this, "此处填写获得的验证码", "此处填写获得的验证码"); EventHandler eventHandler = new EventHandler() { @Override public void afterEvent(int event, int result, Object data) { Message msg = new Message(); msg.arg1 = event; msg.arg2 = result; msg.obj = data; handler.sendMessage(msg); } }; // 注册回调监听接口 SMSSDK.registerEventHandler(eventHandler); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.as_btn_getCode:// 活取验证码 phoneNum = phoneET.getText().toString(); // 判断手机号是否合法 if (!judgephoneNum(phoneNum)) { return; } // 发送短信 SMSSDK.getVerificationCode("86", phoneNum); // 开启线程循环 getCodebtn.setClickable(false); getCodebtn.setText(i + "秒"); new Thread(new Runnable() { @Override public void run() { for (i = 60; i > 0; i--) { handler.sendEmptyMessage(-1); if (i <= 0) { break; } try { Thread.sleep(1000); } catch (Exception e) { } } Looper.prepare(); handler.sendEmptyMessage(-2); } }).start(); break; case R.id.as_btn_submit: new Thread(new Runnable() { @Override public void run() { String code = codeET.getText().toString(); SMSSDK.submitVerificationCode("86", phoneNum, code); flag = false; } }).start(); break; case R.id.as_iv_back: finish(); break; default: break; } } private boolean judgephoneNum(String phoneNum) { if (isMathLength(phoneNum, 11) && isMobilNO(phoneNum)) { return true; } Toast.makeText(getApplicationContext(), "请输入正确的手机号码", Toast.LENGTH_SHORT).show(); return false; } private boolean isMobilNO(String phoneNum) { String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 if (TextUtils.isEmpty(phoneNum)) return false; else return phoneNum.matches(telRegex); } @SuppressLint("NewApi") private boolean isMathLength(String phoneNum, int i) { if (phoneNum.isEmpty()) { return false; } else { return phoneNum.length() == i ? true : false; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { } return super.onKeyDown(keyCode, event); } public class SmsContent extends ContentObserver { private Cursor cursor = null; public SmsContent(Handler handler) { super(handler); } @SuppressWarnings("deprecation") @Override public void onChange(boolean selfChange) { super.onChange(selfChange); // 读取收件箱中指定号码的短信 cursor = managedQuery(Uri.parse("content://sms//inbox"), new String[]{"_id", "address", "read", "body"}, " address=? and read=?", new String[]{"你要监听的号码", "0"}, "_id desc");// 按id排序,如果按date排序的话,修改手机时间后,读取的短信就不准了 Log.e("", "cursor.isBeforeFirst() " + cursor.isBeforeFirst() + " cursor.getCount() " + cursor.getCount()); if (cursor != null && cursor.getCount() > 0) { ContentValues values = new ContentValues(); values.put("read", 1); // 修改为已读 cursor.moveToNext(); int smsbodyColumn = cursor.getColumnIndex("body"); String smsBody = cursor.getString(smsbodyColumn); Log.e("smsBody= ", smsBody); codeET.setText(Utils.getDynamicPassword(smsBody)); } // 在用managedQuery的时候,不能主动调用close()方法,否则在Android 4.0+的系统上,会发生崩溃 if (Build.VERSION.SDK_INT < 14) { cursor.close(); } } } @Override protected void onDestroy() { this.getContentResolver().unregisterContentObserver(content); super.onDestroy(); } }
Utils中的截取短信的功能
/** * 从字符串中截取连续4位数字 * 用于从短信中获取动态密码 * * @param str 短信内容 * @return 截取得到的4位动态密码 */ public static String getDynamicPassword(String str) { Pattern continuousNumberPattern = Pattern.compile("[0-9\\.]+"); Matcher m = continuousNumberPattern.matcher(str); String dynamicPassword = ""; while (m.find()) { if (m.group().length() == 4) { System.out.print(m.group()); dynamicPassword = m.group(); } } return dynamicPassword; }
最后不要忘了添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.WRITE_SMS" /> <uses-permission android:name="android.permission.SEND_SMS" />
布局我就不贴了挺简单的,自己写吧!