Folks!
Я пытаюсь реализовать BroadcastReceiver
для прослушивания входящего сообщения с использованием SMSRetrieverAPI
.
Я получаю сообщения в методе Broadcast onReceive
, но после этого мне нужно передать эту строку сообщений в действие, не перезапуская ее, поэтому я реализовал интерфейс.
Я попробовал приведенный ниже код, но он выдает NullPointerException
для mOTPReceiveListener
. Что-то не работает идеально, поэтому, пожалуйста, поправьте меня.
SMSBroadcastReceiver
как показано ниже
public class SMSBroadcastReceiver extends BroadcastReceiver {
OTPReceiveListener mOTPReceiveListener = null;
public void InitOTPReceiveListener(OTPReceiveListener otpreceivelistener){
this.mOTPReceiveListener = otpreceivelistener;
}
@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:
// Get SMS message contents
String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
Log.e("VERIFY","Full Message : "+message);
if (mOTPReceiveListener != null) {
String[] temp = message.split("-");
String[] msg = temp[1].split(" ");
message = msg[0];
Log.e("VERIFY","message : "+message);
mOTPReceiveListener.onOTPReceived(message);
}
break;
case CommonStatusCodes.TIMEOUT:
// Waiting for SMS timed out (5 minutes)
mOTPReceiveListener.onOTPTimeOut();
break;
}
}
}
public interface OTPReceiveListener {
void onOTPReceived(String otp);
void onOTPTimeOut();
}
}
и код активности
public class VerificationActivity extends BaseActivity implements SMSBroadcastReceiver.OTPReceiveListener
{
Context mContext;
Button btn_verify_submit;
TextView text_resend_otp;
private String TAG = "VERIFY";
private String PHONE = null;
private SmsRetrieverClient mSmsRetrieverClient;
private SMSBroadcastReceiver mSMSBroadcastReceiver;
SMSBroadcastReceiver.OTPReceiveListener mOTPReceiveListener;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
initView();
setClickListener();
PHONE = getIntent().getStringExtra("phone");
Log.e(TAG,"phone : "+PHONE);
mSmsRetrieverClient = SmsRetriever.getClient(this);
startVerify();
mOTPReceiveListener = this;
mSMSBroadcastReceiver = new SMSBroadcastReceiver();
mSMSBroadcastReceiver.InitOTPReceiveListener(this);
}
private void initView()
{
layout_verification_main = findViewById(R.id.layout_verification_main);
overrideFonts(layout_verification_main,VerificationActivity.this);
edt_verify_code = findViewById(R.id.edt_verify_code);
btn_verify_submit = findViewById(R.id.btn_verify_submit);
text_resend_otp = findViewById(R.id.text_resend_otp);
}
private void setClickListener()
{
btn_verify_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Call OTP Match API
}
});
text_resend_otp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Call Resend OTP API
}
});
}
private void startVerify() {
Task<Void> task = mSmsRetrieverClient.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.e(TAG, "SmsRetrievalResult start onSuccess.");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "SmsRetrievalResult start failed.", e);
}
});
}
@Override
public void onOTPReceived(String otp) {
edt_verify_code.setText("" + otp);
Toast.makeText(mContext, "Message OTP : " + otp, Toast.LENGTH_SHORT).show();
Log.e("VERIFY","otp in activity : "+otp);
}
@Override
public void onOTPTimeOut() {
}
}
и я зарегистрировался в манифесте вот так
<receiver android:name=".broadcast.SMSBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
</intent-filter>
</receiver>
Я что-то упустил?