在Android開發中,實現短信驗證碼功能可以通過以下步驟:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
public class SMSReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String messageBody = smsMessage.getMessageBody();
// 在這里處理短信驗證碼
// 可以將短信驗證碼發送給UI界面顯示,或者自動填充到相應的輸入框中
}
}
}
}
}
private SMSReceiver smsReceiver;
@Override
protected void onResume() {
super.onResume();
// 創建IntentFilter對象,并設置接收短信的action
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
// 創建BroadcastReceiver對象
smsReceiver = new SMSReceiver();
// 注冊receiver
registerReceiver(smsReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
// 取消注冊receiver
unregisterReceiver(smsReceiver);
}
通過以上步驟,就可以在Android應用中實現短信驗證碼功能。當接收到短信時,BroadcastReceiver會觸發onReceive()方法,你可以在該方法中處理短信驗證碼。例如,將驗證碼顯示在UI界面上,或者自動填充到相應的輸入框中。