要在Android应用程序中实现自动验证一次性密码,需要在代码中使用BroadcastReceiver。这里是一个示例:
首先,需要添加权限:
然后,在代码中添加BroadcastReceiver:
private BroadcastReceiver mSmsReceiver = new BroadcastReceiver() {
@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");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
if (messages.length > -1) {
String message = messages[0].getMessageBody();
//在这里设置自动验证
}
}
}
}
};
接下来,在onCreate方法中注册BroadcastReceiver:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册接收短信的广播
IntentFilter filter = new IntentFilter();
filter.addAction(SMS_RECEIVED);
registerReceiver(mSmsReceiver, filter);
}
最后,在onDestroy方法中注销BroadcastReceiver:
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mSmsReceiver);
}
以上代码示例可以作为自动验证Android上的一次性密码的解决方法。