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

时间:2016-09-09 05:48:38

标签: android google-cloud-messaging broadcastreceiver one-time-password

我有一个忘记密码页面。我想当otp消息来时它读取otp号码并验证。但在我的情况下OTP消息读取但我只想要OTP号码。 例如,我的OTP消息是: - 9563是您的应用程序重置密码的OTP。将此视为机密。我在这堂课的帮助下阅读了这条消息。但是我想得到的只有OTP号码(9563)。不是整条信息。任何人都可以告诉我该怎么做?

这是我阅读otp消息的类。

    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中打印。但我只想要OTP号而不是整个消息。

1 个答案:

答案 0 :(得分:0)

试试这可能会对你有所帮助

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是根据您的消息内容而不是检查后的内容   它