您的位置:首页 > 移动开发 > Android开发

Android自动读取短信验证码

2015-03-28 12:03 369 查看
实现自动获取手机的短信验证码,原理通过监听短信数据库的变化来解析短信,获取验证码。

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 logan
*
*/
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" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: