Android 之短信验证码自动填写

转载请标明出处:http://blog.csdn.net/qq1221jyj/article/details/47000977

最近做项目。老板提到自动填写后台发送的短信验证码狠人性化,老板的话。就是我们的目标,那就开始做咯。
其实也很简单。不多说直接上代码
public class SmsContent extends ContentObserver{

/**
 * Creates a content observer.
 *
 * @param handler The handler to run {@link #onChange} on, or null if none.
 */
public static final String SMS_URI_INBOX = "content://sms/inbox";
private Activity activity = null;
private String smsContent = "";
private EditText verifyText = null;
private String ergouhaitao="***";


public SmsContent(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", "read" ,"body" },null,null,null);**managedQuery()查看该方法的源码 ,可以了解到更多的功能需求,本人菜鸟,大家自己看源码吧~**

    if (cursor != null) {// 如果短信为未读模式

        cursor.moveToFirst();
        if (cursor.moveToFirst()) {
            **String smsbody = cursor.getString(cursor.getColumnIndex("body"));***这smsbody是收到的短信内容,我是根据短信内容做得处理。*


             String judge= smsbody.replace(" ", "");
            Log.e("judge",judge);
            Log.e("Jyj",judge.contains(ergouhaitao)+"");
                if (judge.contains(ergouhaitao)){
                    String regEx = "[^0-9]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(smsbody.toString());
                    smsContent = m.replaceAll("").trim().toString();
                    verifyText.setText(smsContent);
                }




        }
    }
    if(Build.VERSION.SDK_INT < 14) {
        cursor.close();
    }


}

}

调用时:SmsContent content = new SmsContent(MainActivity.this, new Handler(), main_ed);
this.getContentResolver().registerContentObserver(Uri.parse(“content://sms/”), true, content);

最后别忘了添加权限:


上面的代码就可以直接拿来用了。
小菜比一个,不喜勿喷。大家共同进步。
参考:http://blog.sina.com.cn/s/blog_87dc03ea0101dvus.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值