码迷,mamicode.com
首页 > 移动开发 > 详细

Android自动读取短信验证码

时间:2015-03-30 20:57:43      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

实现自动获取手机的短信验证码,原理通过监听短信数据库的变化来解析短信,获取验证码。

直接附上代码:

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

  

Android自动读取短信验证码

标签:

原文地址:http://www.cnblogs.com/niray/p/4378899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!