要實現自動填充短信驗證碼,你可以使用以下步驟:
SmsRetriever
API來獲取收到的短信。首先,在你的應用中添加以下依賴項:implementation 'com.google.android.gms:play-services-auth:19.2.0'
implementation 'com.google.android.gms:play-services-auth-api-phone:17.5.0'
然后在你的代碼中,使用以下方法來獲取短信:
SmsRetrieverClient client = SmsRetriever.getClient(context);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// SMS retrieval has been started successfully
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Failed to start SMS retrieval
}
});
BroadcastReceiver
中通過以下代碼來解析短信內容:@Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch (status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
// 解析短信內容,獲取驗證碼
break;
case CommonStatusCodes.TIMEOUT:
// SMS retrieval timeout
break;
default:
// Other error occurred
break;
}
}
}
EditText
輸入框,你可以使用以下代碼來填充驗證碼:EditText verificationCodeEditText = findViewById(R.id.verification_code_edit_text);
verificationCodeEditText.setText(verificationCode);
通過上述步驟,你就可以在Android應用中實現自動填充短信驗證碼。