如何停止SmsReceiver?

时间:2018-09-15 08:08:51

标签: android broadcastreceiver

在我的情况下,用户使用电话号码登录,我使用SmsReceiver来获取otp并对其进行身份验证。问题是SmsReceiver并没有停止,并且当用户在另一个页面中并且偶然地 收到另一个短信并且该短信属于我的应用程序时,该应用程序已关闭。

我知道为什么会发生,

  1. 没有任何代码可以在课堂上获得otp
  2. SmsReceiver没有停止

现在,我想知道在使用SmsReceiver后如何将其停止。

我检查了此Stop SMS Receiver,但对我不起作用。

这是我的代码:

AndroidManifest.xml

<receiver android:name=".services.SmsReceiver"
    android:permission="android.permission.BROADCAST_SMS">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

SmsReceiver

public class SmsReceiver extends BroadcastReceiver {

    //interface
    private static ISmsListener mListener;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle data = intent.getExtras();

        Object[] pdus = (Object[]) data.get("pdus");

        for (int i = 0; i < pdus.length; i++) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);

            String sender = smsMessage.getDisplayOriginatingAddress();
            //Check the sender to filter messages which we require to read

            String messageBody = smsMessage.getMessageBody();
            if (messageBody.contains("payment")) {
                mListener.messageReceived(messageBody);
            }
        }
    }

    public static void bindListener(ISmsListener listener) {
        mListener = listener;
    }
}

在登录课程中

// smsReceiver
SmsReceiver.bindListener(messageText -> {
    // If your OTP is six digits number, you may use the below code
    Pattern pattern = Pattern.compile(OTP_REGEX);
    Matcher matcher = pattern.matcher(messageText);
    String otp = null;
    while (matcher.find()) {
        otp = matcher.group();
    }
    codeNumberEdt.setText(otp);
    try {
        //set time in mili
        Thread.sleep(3000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    LoginRegisterPresenter.callCheckCode(mobile, otp);
});

1 个答案:

答案 0 :(得分:0)

我查看了您的代码,您的问题将得到解决。您可以在登录类中使用此代码

private void enableSmsReceiver(){
    ComponentName receiver = new ComponentName(this, SmsReceiver.class);
        PackageManager pm = this.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                        PackageManager.DONT_KILL_APP);
}
private void disableSmsReceiver() {
    ComponentName receiver = new ComponentName(this, SmsReceiver.class);
    PackageManager pm = this.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
}