仅在 运行 中的 Activity 时接收短信

Receive SMS Messages only when Activity in Running

我正在构建一个 Android 应用程序,它接收 SMS 消息并显示来自特定 gateway/sender 的消息。

问题是,如果我在 AndroidManifest 文件中声明接收者,它会一直接收来自所有人的消息,即使应用是 paused/closed。每当我不在应用程序上时收到短信,这都会导致应用程序强制崩溃。

这是我在 ReceieveMessage.java

中的代码
package com.phoenix.omnisurf;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class ReceiveMessage extends BroadcastReceiver {

private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public static String messageBody = "";

@Override
public void onReceive(Context context, Intent intent) {
    final Bundle bundle = intent.getExtras();
    if (bundle != null) {

        messageBody = "";

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

        for (int i = 0; i < pdus.length; i++) {
            SmsMessage messageHandler = SmsMessage.createFromPdu((byte[]) pdus[i]);
            messageBody += messageHandler.getDisplayMessageBody();
        }

        SurfActivity.mThis.messageContainer.setText(messageBody);
    }
}
}

我的清单上还注册了以下接收器:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

    <!-- Message Receiver -->
    <receiver android:name=".ReceiveMessage">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

如何创建仅在特定 activity 打开或应用 运行 时才打开的广播接收器?

只需检查您的 Activity 是否在前台

将此添加到您的 Activity private static boolean isInForeground;

onResume(){
 super.onResume();
 isInForground = true;
}

onPause(){
 super.onPause();
 isInForground = false;
}

然后在您的接收器中class检查

 if(SurfActivity.isInForeground){
   SurfActivity.mThis.messageContainer.setText(messageBody);
}

您可以动态注册您的接收器:

@Override
protected void onResume() {
    super.onResume();
    final IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mBroadcastReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mBroadcastReceiver);
}