我创建了一个包含OTP验证部分的应用程序。我能够在接收时获取消息,但是我在记录消息正文时将其作为两部分显示 -
我的onReceive功能是
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
bundle = intent.getExtras();
if (bundle != null) {
Object[] pdu_Objects = (Object[]) bundle.get("pdus");
if (pdu_Objects != null) {
prgDialog.setVisibility(View.GONE);
for (Object aObject : pdu_Objects) {
currentSMS = getIncomingMessage(aObject, bundle);
String senderNo = currentSMS.getDisplayOriginatingAddress();
message = currentSMS.getDisplayMessageBody();
String sndr = "SENDER";
if(senderNo.toLowerCase().contains(sndr.toLowerCase())) {
String CurrentString = message;
try {
String[] separated = CurrentString.split("OTP");
***otp2 = separated[1].trim().substring(2, 6);***
if (otp2.matches("[0-9]+") && otp2.length() == 4) {
otp_val.setText(otp2);
} else {
prgDialog.setVisibility(View.GONE);
}
} catch (Exception e) {
Log.e("exception", "" + e);
}
}
}
this.abortBroadcast();
}
}
}
}
private SmsMessage getIncomingMessage(Object aObject, Bundle bundle) {
SmsMessage currentSMS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = bundle.getString("format");
currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
} else {
currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
}
return currentSMS;
}
在按字符串 OTP 拆分邮件后,尝试使用子字符串分隔1 时,我收到错误ArrayIndexOutOfBoundsException
。
结果作为图像附加。
答案 0 :(得分:0)
你试图使用错误的子串使用
String otp2 = separated[1].trim().substring(0, 4);
如下面的代码
try {
String[] separated = CurrentString.split("OTP");
String otp2 = separated[1].trim().substring(0, 4);
if (otp2.matches("[0-9]+") && otp2.length() == 4) {
otp_val.setText(otp2);
} else {
prgDialog.setVisibility(View.GONE);
}
} catch (Exception e) {
Log.e("exception", "" + e);
}