要實現自動獲取短信驗證碼功能,你可以使用以下步驟:
1. 在AndroidManifest.xml文件中添加以下權限:
<uses-permission android:name="android.permission.RECEIVE_SMS" /><uses-permission android:name="android.permission.READ_SMS" />
2. 創建一個BroadcastReceiver類來接收短信:
public class SMSReceiver extends BroadcastReceiver {private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
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();
// 在這里處理短信內容
}
}
}
}
}
}
3. 在你的Activity中注冊SMSReceiver:
private SMSReceiver smsReceiver;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsReceiver = new SMSReceiver();
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
這樣,當你的應用在前臺運行時,SMSReceiver將會自動接收到短信并在onReceive方法中處理短信內容。你可以根據自己的需求對短信內容進行解析,獲取驗證碼等操作。請注意,由于Android 4.4及以上版本對SMS_RECEIVED廣播進行了限制,只有用戶選擇你的應用作為默認短信應用時,才能收到短信。