仅在某些 activity 上使用 broadcastreceiver

Using broadcastreceiver only on certain activity

我有两个活动是 Register(),另一个是 ReadNews()。我正在使用广播接收器自动检测互联网连接以执行一些代码。

 public void onReceive(Context context, Intent intent) {

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
    Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        if(MyApplication.isActivityVisible() == true) {
            Log.d("WifiReceiver", "Have Wifi Connection");
            Toast.makeText(context, "تم الإتصال بالشبكة", Toast.LENGTH_LONG).show();
            if (context instanceof RegisterActivity){
                Intent i = new Intent(context,
                        ReadNews.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
            else {

            }
        }
    }

如何在用户仍在使用 RegisterActivity() 时仅在互联网连接继续时才启动 ReadNews() activity?
我尝试使用 if (context instanceof RegisterActivity) 之类的上下文,但这似乎不正确。

感谢@Squonk 的评论,我已经按照简短的评论说明完成了我想做的事情,现在我想分享我的代码摘要以展示它是如何工作的:
内部广播接收器class

 private BroadcastReceiver wifiReceiver =
        new BroadcastReceiver() {

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

    //do what ever you want here
};

在 onResume() 中注册广播接收器

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //or any intent filter you want 
    registerReceiver(wifiReceiver, filter);
}

在 onPause 中注销广播接收器

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

重要

不要在清单中使用 <intent-filter>。 注册广播接收器必须是动态的 (onResume,onPause)

正如我在评论中所说,您不需要内部 class,您可以创建一个独立的 class,如下所示:

public class MyWifiReceiver extends BroadcastReceiver {

    private Activity activityToFinish;

    MyWifiReceiver(Activity activityToFinish) {
        this.activityToFinish = activityToFinish;
    }

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

        // do what ever you want here
        ...
        // finish the activity
        activityToFinish.finish();
    }
}

并在RegisterActivity中声明一个私有成员变量,如下所示:

 private MyWifiReceiver wifiReceiver;

RegisterActivity.onCreate()中创建一个在构造函数中传递Activity的接收器实例,像这样:

    wifiReceiver = new MyWifiReceiver(this);

然后注册和取消注册 wifiReceiver,如您在自己的答案中所示。