所以我正在开发一个像WhatsApp这样的验证系统,用户输入通过短信收到的代码并将代码发送回服务器.. yada yada ..all那些基本的东西。
我的困境是我已经正确接收并阅读了短信。如何过滤身体,以便它自动将数字(不是电话号码,但验证码)传递给editText。我试图避免用户手动输入验证码。 Lemme在下面显示了一些代码。
public void processReceive(Context context, Intent intent){
Bundle bundle = intent.getExtras();
if(bundle == null){
return;
}
Object[] objectArray = (Object[])bundle.get("pdus");
for(int i = 0; i < objectArray.length; i++){
SmsMessage smsMsg = SmsMessage.createFromPdu((byte[])objectArray[i]);
String smsBody = smsMsg.getMessageBody();
Toast.makeText(context, smsBody, Toast.LENGTH_SHORT).show();
}
}
//在上面的代码中,我的broadcastReceiver接收短信,我可以在祝酒词中显示正文。短信是这样的:“你的验证码:12345”。
我如何从短信中获取代码并以编程方式将其值发送到editText,就像WhatsApp那样。
number = (EditText) findViewById(R.id.number);
谢谢。非常感谢您输入
答案 0 :(得分:1)
试试这可能会对你有所帮助
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);
number.setText(otp);
}
答案 1 :(得分:1)
您可以使用分割功能获取最后5个数字:
String[] splited = body.split(":");
String mylastnum= splited[1];
number.settext(mylastnum);
希望它有所帮助!
答案 2 :(得分:0)
使用下面提到的代码在Android清单中注册Broad Cast Receiver。
<!-- SMS Receiver -->
<receiver android:name=".receiver.SmsReceiver">
<intent-filter android:priority="99999">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
使用下面提到的代码创建Broad Cast Receiver。
@覆盖 public void onReceive(Context context,Intent intent){
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (Object aPdusObj : pdusObj) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
String senderAddress = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.e(TAG, "Received SMS: " + message + ", Sender: " + senderAddress);
// if the SMS is not from our gateway, ignore the message
if (!senderAddress.toLowerCase().contains(Config.SMS_ORIGIN.toLowerCase())) {
Log.e(TAG, "SMS is not for our app!");
return;
}
// verification code from sms
String verificationCode = getVerificationCode(message);
Log.e(TAG, "OTP received: " + verificationCode);
Intent hhtpIntent = new Intent(context, HttpService.class);
hhtpIntent.putExtra("otp", verificationCode);
context.startService(hhtpIntent);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
通过短信发送的解析验证码。
private String getVerificationCode(String message){ 字符串代码= null; int index = message.indexOf(Config.OTP_DELIMITER);
if (index != -1) {
int start = index + 2;
int length = 6;
code = message.substring(start, start + length);
return code;
}
return code;
}