实现自动获取手机的短信验证码,原理通过监听短信数据库的变化来解析短信,获取验证码。
直接附上代码:
1.建立一个监听数据库的类
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; /** * 监听短信数据库,自动获取短信验证码 * * @author 贾亚光 * @date 2015-3-25 * */ public class AutoGetCode extends ContentObserver { private Cursor cursor = null; private Activity activity; private String smsContent = ""; private EditText editText = null; public AutoGetCode(Activity activity, Handler handler, EditText edittext) { super(handler); this.activity = activity; this.editText = edittext; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); // 读取收件箱中指定号码的短信 cursor = activity.managedQuery(Uri.parse("content://sms/inbox"), new String[] { "_id", "address", "read", "body" }, "address=? and read=?", new String[] {"你要截获的电话号码", "0" }, "_id desc"); // 按短信id排序,如果按date排序的话,修改手机时间后,读取的短信就不准了 if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); if (cursor.moveToFirst()) { String smsbody = cursor .getString(cursor.getColumnIndex("body")); String regEx = "(?<![0-9])([0-9]{" + 6 + "})(?![0-9])"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(smsbody.toString()); while (m.find()) { smsContent = m.group(); editText.setText(smsContent); } } } } }
2.在使用的时候在activity中注册
AutoGetCode autoGetCode = new AutoGetCode(RegistCode.this, new Handler(), regist_code);//regist_code 要显示验证码的EditText // 注册短信变化监听 this.getContentResolver().registerContentObserver( Uri.parse("content://sms/"), true, autoGetCode);
3.在合适的地方取消注册
@Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); this.getContentResolver().unregisterContentObserver(autoGetCode); }
4.最后别忘记了添加权限
<!-- 读写短信的权限 --> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.WRITE_SMS" />
这样就可以了。
参考资料:
http://blog.sina.com.cn/s/blog_87dc03ea0101dvus.html
http://www.it165.net/pro/html/201406/15300.html