如何从android服务器发送的OTP消息中获取唯一的OTP号码?

How to get the only OTP number from the OTP message send by the server in android?

我有一个忘记密码页面。我想当 otp 消息到来时它读取 otp 号码和 verify.But 在我的情况下读取 OTP 消息但我只想要 OTP 号码。 例如我的 OTP 消息是:- 9563 是您的应用程序重置密码的 OTP。将此视为机密。我在 class.but 的帮助下阅读了这条消息,我只想获得像 (9563) 这样的 OTP 号码。而不是整个 message.Can 有人告诉我我该怎么做吗??

这是我用来阅读 otp 消息的 class。

    public class IncominMsg extends BroadcastReceiver {

    final SmsManager smsManager = SmsManager.getDefault();
    Context mContext;
    Object[] pdusObj;
    String message;


    @Override
    public void onReceive(Context context, Intent intent) {


        final Bundle bundle = intent.getExtras();


        try {
            if (bundle != null) {
                pdusObj = (Object[]) bundle.get("pdus");
                SmsMessage[] smsMessages = new SmsMessage[pdusObj.length];

                for (int i = 0; i < pdusObj.length; i++) {
                    smsMessages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);

                    message = smsMessages[i].getDisplayMessageBody();
                    Log.e("message..", message);
                }


                Pattern generalOtpPattern = Pattern.compile(message);
                Matcher generalOtpMatcher = generalOtpPattern.matcher(smsMessages[0].getMessageBody().toString());

                if (generalOtpMatcher.find()) {
                    String otp = generalOtpMatcher.group(1);//this is only your OTP code


                }


            }


        } catch (Exception e) {

        }
    }


}

我收到消息并打印在 logcat.but 我只想要 OTP 号码而不是整个消息。

试试这个可能对你有帮助

public static String GENERAL_OTP_TEMPLATE = "Your verification code: (.*).";

SmsMessage[] message = new SmsMessage[objectArray.length];
for (int i = 0; i < objectArray.length; i++) {
 message[i] = SmsMessage.createFromPdu((byte[]) objectArray[i]);

}
Pattern generalOtpPattern = Pattern.compile(GENERAL_OTP_TEMPLATE);
Matcher generalOtpMatcher = generalOtpPattern.matcher(message[0].getMessageBody().toString());

if (generalOtpMatcher.find()) {
   String otp = generalOtpMatcher.group(1);//this is only your OTP code

}

make GENERAL_OTP_TEMPLATE is as per you message content and than after check it.