Android automatically reads the SMS verification code and fills it in.
To automatically read SMS verification codes in an Android app and fill in the corresponding fields, you can follow these steps:
- Add permission: Include the permission to read SMS in the AndroidManifest.xml file.
<uses-permission android:name="android.permission.READ_SMS" />
- Create a BroadcastReceiver: Develop a class that extends BroadcastReceiver to listen for incoming SMS events.
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.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();
// 在这里处理短信内容,提取验证码并填入相应的字段
}
}
}
}
}
}
- Register the BroadcastReceiver: Register the BroadcastReceiver in the onCreate method of the Activity where you need to read the verification code.
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
SmsReceiver smsReceiver = new SmsReceiver();
registerReceiver(smsReceiver, intentFilter);
- Extract the verification code and fill in the field: In the onReceive method of SmsReceiver, you can extract the verification code using regular expressions or other methods, and then fill it into the corresponding field.
For example, assuming the format of the verification code is “[App Name] Code: 123456, do not disclose to others”, you can use regular expressions to extract the code.
Pattern pattern = Pattern.compile("验证码:(\\d+)");
Matcher matcher = pattern.matcher(messageBody);
if (matcher.find()) {
String verificationCode = matcher.group(1);
// 将验证码填入相应的字段
}
- Due to restrictions in Android versions 4.4 and above, it is not possible to directly access the contents of other apps’ messages. If you need to read the verification codes from other apps’ messages, users will need to manually authorize it or set the app as the default messaging app.
- Reading the SMS verification code requires user authorization and can be authorized through runtime permissions.
These are the basic steps for automatically reading SMS verification codes in an Android application and filling them into the corresponding fields. Depending on the specific application scenario and requirements, some adaptive adjustments and optimizations may also be needed.