Why BroadcastReceiver works even when app is in background ?

后端 未结 9 908
感动是毒
感动是毒 2020-12-04 13:59

I am checking Internet connectivity in my app using BroadcastReceiver and I show an alert dialog if the connection is lost. It works fine. But my problem is that BroadcastRe

9条回答
  •  既然无缘
    2020-12-04 14:06

    You should register/unregister your BroadcastReceiver in onPause() and onResume() of each activity. Then you know that the receiver is only "listening" when your app is in the foreground. You can easily do that by creating your own BaseActivity that extends Activity and overrides onPause() and onResume() and registers/unregisters your receiver. Just have all your activities extend BaseActivity and have them call through to super.onResume() and super.onPause() as usual. Here's example code:

    public class BaseActivity extends Activity {
        // Create an IntentFilter to listen for connectivity change events
        static IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
        // Create an instance of our BroadcastReceiver
        static ConnectivityChangedReceiver receiver = new ConnectivityChangedReceiver();
    
        @Override
        protected void onPause() {
            super.onPause();
            // Stop listening for connectivity change events
            unregisterReceiver(receiver);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            // Listen for connectivity change events
            registerReceiver(receiver, filter);
        }
    }
    

    All your activities should extend BaseActivity and if they need to do anything special in onResume() or onPause() just make sure to call through to super.onXXXXX() like this:

    public MyActivity extends BaseActivity {
        @Override
        protected void onResume() {
            super.onResume();
            // Here you do whatever you need to do in onResume() of your activity
            ...
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            // Here you do whatever you need to do in onPause() of your activity
            ...
        }
    }
    

    I didn't run the code through a compiler so I apologize if there's a typo or I missed something.

提交回复
热议问题