我正在使用SMS Retriever API来检索SMS内容,但是mt广播接收器没有获取SMS内容。我已经创建了Register并从Retriever API开始侦听服务。我也已经在清单文件中声明了此广播。
<receiver android:name="broadcastreceivers.SMSReceiver" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
</intent-filter>
</receiver>
这是我的代码。
public class VerifyOTP extends AppCompatActivity implements SMSReceiver.OTPReceiveListener {
private SMSReceiver smsReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
startSMSListener();
}
// onDestroy
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver( smsReceiver );
}
// to start and listen for SMS...
private void startSMSListener() {
try {
smsReceiver = new SMSReceiver();
smsReceiver.setOTPListener( this );
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction( SmsRetriever.SMS_RETRIEVED_ACTION );
this.registerReceiver( smsReceiver, intentFilter );
SmsRetrieverClient client = SmsRetriever.getClient( this );
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener( aVoid -> {
// API successfully started
} );
task.addOnFailureListener( e -> {
// Fail to start API
} );
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onOTPReceived(String otp) {
Log.d( TAG, "onOTPReceived: " + otp );
unregisterReceiver( smsReceiver );
}
}
这是我的SMSReceiver广播。
公共类SMSReceiver扩展了BroadcastReceiver {
private OTPReceiveListener otpListener;
public void setOTPListener(OTPReceiveListener otpListener) {
this.otpListener = otpListener;
}
@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 );
switch (status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
//This is the full message
String message = (String) extras.get( SmsRetriever.EXTRA_SMS_MESSAGE );
//Extract the OTP code and send to the listener
if (otpListener != null) {
otpListener.onOTPReceived( message );
}
break;
}
}
}
// callbacks...
public interface OTPReceiveListener {
void onOTPReceived(String otp);
void onOTPTimeOut();
void onOTPReceivedError(String error);
}
}
这是我的消息格式。
<#> CompanyName : Your verification code is OTPCode.
HexString.