本文实例为大家分享了android实现手机自动获取短信验证码功能,供大家参考,具体内容如下
1、短信监听广播
2、读取短信内容
3、截取短信内容【可以 reg截取】
4、填写至相应控件
ps:devstore测试没有获取到验证码
源码片段
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
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通过手机自动获取短信验证码的详细代码,希望对大家实现手机自动获取短信验证码有所帮助。