如何阻止SmsReceiver?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何阻止SmsReceiver?相关的知识,希望对你有一定的参考价值。
在我的情况下,用户使用电话号码登录,我使用SmsReceiver
获取otp并对其进行身份验证。问题是SmsReceiver
没有停止,当用户在另一个页面并且意外地另一个短信接收并且属于我的应用程序时,应用程序已关闭。
我知道为什么会这样,
- 没有任何代码可以在课堂上获得otp
- 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);
});
答案
我查看了您的代码,您的问题将得到解决。您可以在登录类中使用此代码
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);
}
以上是关于如何阻止SmsReceiver?的主要内容,如果未能解决你的问题,请参考以下文章
Wordpress阻止访问wp admin€“wpsnipp.com网站你博客的Wordpress代码片段