当 activity and/or 应用程序关闭时保留广播接收器 运行?

Keep broadcast receiver running when activity and/or app is closed?

我有一个 activity,我可以在其中点击一个按钮来启动 BroadcastReceiver,它会监听 wifi 连接的变化。现在,当显示 activity 或我离开应用程序(按主页按钮)而 activity 正在显示时,接收器工作正常。但是,如果我结束 activity 或将整个应用程序终止(即在最近的任务列表中将其刷掉),接收器将不再工作。我的 activity 包含接收器的结构如下所示:

MainActivity.java

...

public class MainActivity extends AppCompatActivity {
...
    public BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
        ...
        }
    }
}

我已经阅读了有关 ServicesJobSchedulers 的信息,并认为我可能必须随时使用其中之一来获取我的接收器 运行。我只是真的不知道如何实现这些。谁能向我解释该怎么做? 另外,将 BroadcastReceiver 包含在 MainActivity class 中是个好主意还是我应该在单独的 class 中定义它?

非常感谢!

您正在创建上下文注册接收器,根据 docs:

Context-registered receivers receive broadcasts as long as their registering context is valid. For an example, if you register within an Activity context, you receive broadcasts as long as the activity is not destroyed. If you register with the Application context, you receive broadcasts as long as the app is running.

您可以在单独的文件中创建您的 BR 并将其注册到您的清单文件中,以便在匹配您的 intent 过滤器时调用它:

<receiver android:name=".wifiStateReceiver"  android:exported="true">
    <intent-filter>
       <action android:name="android.net.wifi.STATE_CHANGE" />
    </intent-filter>
</receiver>

当 Intent 过滤器匹配时,您的 BR 内的 onReceive 方法将被调用。

public class wifiStateReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {
      //do some quick processing and call an activity
   }
}