在注册,实名认证、修改手机号码的,我们都会用发送验证码的功能,在这里经常就会涉及到2个效果,
第一个:发送验证码倒计时效果;
第二个:自动获取接收到的短信,并且填充验证码。
先来说倒计时效果:
其实很简单,就是一个计时器。每秒刷新一次,倒计时完了。就可以重新点击获取了。
<pre name="code" class="java">btn_getYzm.setEnabled(false);btn_getYzm.setBackgroundResource(R.drawable.daojishi);task = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { // UI thread @Override public void run() { if (time <= 0) { // 当倒计时小余=0时记得还原图片,可以点击 btn_getYzm.setEnabled(true); btn_getYzm.setBackgroundResource(R.drawable.btn_yangzhengma_selector); btn_getYzm.setTextColor(Color.parseColor("#454545")); btn_getYzm.setText("获取验证码"); task.cancel(); } else { btn_getYzm.setText(time + "秒后重试"); btn_getYzm.setTextColor(Color.rgb(125, 125, 125)); } time--; } }); }};time = 60;timer.schedule(task, 0, 1000);
第二个,自动监听新短信,并解析里面的验证码
package com.smsyzm;import java.util.regex.Matcher;import java.util.regex.Pattern;import android.app.Activity;import android.database.ContentObserver;import android.database.Cursor;import android.net.Uri;import android.os.Handler;import android.widget.EditText;/** * 注册、实名认证、修改手机号码,自动获取验证码,并且填上 * */public class GetSmsContent extends ContentObserver { public final String SMS_URI_INBOX = "content://sms/inbox"; private Activity activity = null; private String smsContent = ""; private EditText verifyText = null; private String SMS_ADDRESS_PRNUMBER = "400888666";//短息发送提供商 public GetSmsContent(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.managedQuery(Uri.parse(SMS_URI_INBOX), new String[] { "_id", "address", "body", "read" }, //要读取的属性 "address=? and read=?", //查询条件是什么 new String[] { SMS_ADDRESS_PRNUMBER, "0" },//查询条件赋值 "date desc");//排序 if (cursor != null) {// 如果短信为未读模式 cursor.moveToFirst(); if (cursor.moveToFirst()) { String smsbody = cursor.getString(cursor.getColumnIndex("body")); System.out.println("smsbody=======================" + smsbody); String regEx = "[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(smsbody.toString()); smsContent = m.replaceAll("").trim().toString(); if(verifyText != null && null!=smsContent && !"".equals(smsContent)){ verifyText.setText(smsContent); verifyText.setSelection(smsContent.length()); } } } }}
调用方法:在Activity的oncreate方法里面注册:
GetSmsContent content = new GetSmsContent(RegisterByPhone.this, new Handler(), edit_yzm);
// 注册短信变化监听
this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content);
demo完整的下载链接 点击打开链接