Android如何通过手机自动获取短信验证码
程序员文章站
2024-02-24 10:50:04
本文实例为大家分享了android实现手机自动获取短信验证码功能,供大家参考,具体内容如下
1、短信监听广播
2、读取短信内容
3、截取短信内容【可以 reg截取】...
本文实例为大家分享了android实现手机自动获取短信验证码功能,供大家参考,具体内容如下
1、短信监听广播
2、读取短信内容
3、截取短信内容【可以 reg截取】
4、填写至相应控件
ps:devstore测试没有获取到验证码
源码片段
public class mainactivity extends activity { private broadcastreceiver smsreceiver; private intentfilter filter2; private handler handler; private edittext et; private string strcontent; private string patterncoder = "(?<!--\\d)\\d{6}(?!\\d)"; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); et = (edittext) findviewbyid(r.id.et); handler = new handler() { public void handlemessage(android.os.message msg) { et.settext(strcontent); }; }; filter2 = new intentfilter(); filter2.addaction("android.provider.telephony.sms_received"); filter2.setpriority(integer.max_value); smsreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { object[] objs = (object[]) intent.getextras().get("pdus"); for (object obj : objs) { byte[] pdu = (byte[]) obj; smsmessage sms = smsmessage.createfrompdu(pdu); // 短信的内容 string message = sms.getmessagebody(); log.d("logo", "message " + message); // 短息的手机号。。+86开头? string from = sms.getoriginatingaddress(); log.d("logo", "from " + from); time time = new time(); time.set(sms.gettimestampmillis()); string time2 = time.format3339(true); log.d("logo", from + " " + message + " " + time2); strcontent = from + " " + message; handler.sendemptymessage(1); if (!textutils.isempty(from)) { string code = patterncode(message); if (!textutils.isempty(code)) { strcontent = code; handler.sendemptymessage(1); } } } } }; registerreceiver(smsreceiver, filter2); } @override protected void ondestroy() { super.ondestroy(); unregisterreceiver(smsreceiver); } /** * 匹配短信中间的6个数字(验证码等) * * @param patterncontent * @return */ private string patterncode(string patterncontent) { if (textutils.isempty(patterncontent)) { return null; } pattern p = pattern.compile(patterncoder); matcher matcher = p.matcher(patterncontent); if (matcher.find()) { return matcher.group(); } return null; } }</pre-->
文章末尾为大家在分享两个专题,供大家参考:
以上就是android通过手机自动获取短信验证码的详细代码,希望对大家实现手机自动获取短信验证码有所帮助。
推荐阅读