首先定义一个广播接收者接受系统短信广播,对收到短信的广播进行判断,如果是目标号码就进行验证码的解析,并实现接口返回给调用处。
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.telephony.SmsMessage; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SMSReceiver extends BroadcastReceiver { public interface ISMSListener { public void onSmsReceive(String verifyCode); } private static ISMSListener mSMSListener; public SMSReceiver(ISMSListener ismsListener) { mSMSListener = ismsListener; } public static final String TAG = "ImiChatSMSReceiver"; //android.provider.Telephony.SMSReceiver.Intents public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(SMS_RECEIVED_ACTION)) { SmsMessage[] messages = getMessagesFromIntent(intent); for (SmsMessage message : messages) { // LogUtil.d(message.getOriginatingAddress() + " : " + // // message.getDisplayOriginatingAddress() + " : " + // // message.getDisplayMessageBody() + " : " + // // message.getTimestampMillis()); // 在这里你可以对放松的号码进行判断,只接受目标号码的验证码 String msg = message.getDisplayMessageBody(); String verifyCode = null; Pattern p = Pattern.compile("//d{6}");//这里你可以更改数字来指定验证码的位数 Matcher m = p.matcher(msg); while (m.find()) { verifyCode = m.group(); break; } if (mSMSListener != null) { mSMSListener.onSmsReceive(verifyCode); } } } } public final SmsMessage[] getMessagesFromIntent(Intent intent) { Object[] messages = (Object[]) intent.getSerializableExtra("pdus"); byte[][] pduObjs = new byte[messages.length][]; for (int i = 0; i < messages.length; i++) { pduObjs[i] = (byte[]) messages[i]; } byte[][] pdus = new byte[pduObjs.length][]; int pduCount = pdus.length; SmsMessage[] msgs = new SmsMessage[pduCount]; for (int i = 0; i < pduCount; i++) { pdus[i] = pduObjs[i]; msgs[i] = SmsMessage.createFromPdu(pdus[i]); } return msgs; } }
Activity实现接口并注册广播。
public class MainActivity extends AppCompatActivity implements SMSReceiver.ISMSListener { private SMSReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mReceiver =new SMSReceiver(this); IntentFilter filter = new IntentFilter(); filter.addAction("android.provider.Telephony.SMS_RECEIVED"); registerReceiver(mReceiver,filter); } @Override public void onSmsReceive(String verifyCode) { Toast.makeText(this, "验证码为:" + verifyCode, Toast.LENGTH_SHORT).show(); //获取验证码并填写到EditText中,即可 } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); } }
添加权限:
<uses-permission android:name=”android.permission.RECEIVE_SMS”></uses-permission><uses-permission android:name=”android.permission.READ_SMS”></uses-permission>
OK搞定。