我试图通过其广播接收器使用 SmsRetrieverClient 获取短信,实际问题是当 SMS 出现时 onReceive 永远不会调用以进一步处理它,但稍后会在 5 分钟后调用接收器的超时方法。
实际上,我尝试使用库来获取 SMS 并使其正常工作,但要求获得 SMS 读取权限,不幸的是,在将应用程序上传到 Playstore 时,这将面临 Google 政策问题。
下面是我的代码。
下面是我的 Activity 中的 SmsRetrieverClient 方法:
private void startSMSListener() {
SmsRetrieverClient smsRetrieverClient = SmsRetriever.getClient(this);
Task<Void> retriever = smsRetrieverClient.startSmsRetriever();
retriever.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
SMSBroadcastReceiver.OTPListener otpListener = new SMSBroadcastReceiver.OTPListener() {
@Override
public void onOTPReceived(String otpData) {
inputOTP.setText(otpData);
}
@Override
public void onOTPTimeOut() {
inputOTP.setText("");
Toast.makeText(ctx, "TimeOut", Toast.LENGTH_SHORT).show();
}
};
smsBroadcastReceiver.injectOTPListener(otpListener);
registerReceiver(smsBroadcastReceiver, new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION));
}
});
retriever.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(ctx, "Problem to start listener", Toast.LENGTH_SHORT).show();
}
});
}
下面的代码是从广播接收器接收短信:
public class SMSBroadcastReceiver extends BroadcastReceiver {
private OTPListener otpReceiver;
public void injectOTPListener(OTPListener receiver) {
this.otpReceiver = receiver;
}
@Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
System.out.println("SMS verification code::SMSBroadcastReceiver:0: "+ status);
switch (status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
String message = (String)extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
Pattern pattern = Pattern.compile("\\d{4}");
Matcher matcher = pattern.matcher(message);
System.out.println("SMS verification code::SMSBroadcastReceiver:1: "+ message);
if (matcher.find()) {
if (otpReceiver != null){
otpReceiver.onOTPReceived(matcher.group(0));
}
}
break;
case CommonStatusCodes.TIMEOUT:
System.out.println("SMS verification code::SMSBroadcastReceiver:2: TIMEOUT");
if (otpReceiver != null){
otpReceiver.onOTPTimeOut();
}
break;
}
}
}
public interface OTPListener {
void onOTPReceived(String otp);
void onOTPTimeOut();
}
}
在清单中:
<receiver android:name=".SMSBroadcastReceiver"
android:exported="true">
<intent-filter>
<action
android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
</intent-filter>
</receiver>