Android自动读取短信验证码
实现自动获取手机的短信验证码,原理通过监听短信数据库的变化来解析短信,获取验证码。
直接附上代码:
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);
}
}
}
}
/**
* 从短信字符窜提取验证码
* @param body 短信内容
* @param YZMLENGTH 验证码的长度 一般6位或者4位
* @return 接取出来的验证码
*/
public static String getyzm(String body, int YZMLENGTH) {
// 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合
// (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
// (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现
Pattern p = Pattern
.compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])");
Matcher m = p.matcher(body);
if (m.find()) {
System.out.println(m.group());
return m.group(0);
}
return null;
}
}
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