Android自动填写获取到的验证码
Android需要添加的相关权限
1 <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> 2 <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
相关的代码:
1 package com.dongdongsongcan.app; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 import android.telephony.SmsMessage; 7 8 import com.su.dolphin.utils.LogUtil; 9 10 import java.util.ArrayList; 11 import java.util.List; 12 import java.util.regex.Matcher; 13 import java.util.regex.Pattern; 14 15 public class SMSReceiver extends BroadcastReceiver 16 17 { 18 19 public interface ISMSListener { 20 public void onSmsReceive(String verifyCode); 21 } 22 23 private static ISMSListener mSMSListener; 24 25 public SMSReceiver(ISMSListener ismsListener) { 26 mSMSListener = ismsListener; 27 } 28 29 public static final String TAG = "ImiChatSMSReceiver"; 30 31 //android.provider.Telephony.Sms.Intents 32 33 public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; 34 35 36 @Override 37 38 public void onReceive(Context context, Intent intent) 39 40 { 41 LogUtil.d(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); 42 if (intent.getAction().equals(SMS_RECEIVED_ACTION)) 43 44 { 45 46 SmsMessage[] messages = getMessagesFromIntent(intent); 47 48 for (SmsMessage message : messages) 49 50 { 51 52 // LogUtil.d(message.getOriginatingAddress() + " : " + 53 // 54 // message.getDisplayOriginatingAddress() + " : " + 55 // 56 // message.getDisplayMessageBody() + " : " + 57 // 58 // message.getTimestampMillis()); 59 60 61 String msg = message.getDisplayMessageBody(); 62 LogUtil.d("MSG: " + msg); 63 String verifyCode = null; 64 Pattern p = Pattern.compile("\\d{4}"); 65 Matcher m = p.matcher(msg); 66 while (m.find()) { 67 verifyCode = m.group(); 68 break; 69 } 70 LogUtil.d("verifyCode " + verifyCode); 71 if (mSMSListener != null) { 72 mSMSListener.onSmsReceive(verifyCode); 73 } 74 } 75 76 } 77 78 } 79 80 81 public final SmsMessage[] getMessagesFromIntent(Intent intent) 82 83 { 84 85 Object[] messages = (Object[]) intent.getSerializableExtra("pdus"); 86 87 byte[][] pduObjs = new byte[messages.length][]; 88 89 90 for (int i = 0; i < messages.length; i++) 91 92 { 93 94 pduObjs[i] = (byte[]) messages[i]; 95 96 } 97 98 byte[][] pdus = new byte[pduObjs.length][]; 99 100 int pduCount = pdus.length; 101 102 SmsMessage[] msgs = new SmsMessage[pduCount]; 103 104 for (int i = 0; i < pduCount; i++) 105 106 { 107 108 pdus[i] = pduObjs[i]; 109 110 msgs[i] = SmsMessage.createFromPdu(pdus[i]); 111 112 } 113 114 return msgs; 115 116 } 117 118 119 }
不定期会发布一些实用的Java开发文章