Checking the Networking Connectivity using BroadcastReceiver in Android

前端 未结 2 609
长情又很酷
长情又很酷 2020-12-02 21:37

I am using the BroadcastReceiver to check the network connectivity while my app is running.I have binded the BroadcastReceiver with the Activity inorder to bring few contro

相关标签:
2条回答
  • 2020-12-02 22:07

    Flo's option one is correct for making Broadcast Receiver global by including in manifest file. there is another option is, make a activity as base activity and extends all your activity with this and register you receiver in base activity.

    0 讨论(0)
  • 2020-12-02 22:31

    I think you got 2 options.

    First option

    First you should register your receiver not with code but within the manifest file. By this way it is registered automatically for your application. Within you receiver you have to store the current state of the network somewhere centrally perhaps in a custom Application class or a singleton class.

    Implement some kind of observer pattern so that your activities could register themselves to your custom Application class which holds the network state. The Application class then informs every registered activity about the change of the network state.

    You activity class register and unregister to/from the Application class in onCreate() and onDestroy() (better would be onResume() and onPause()) so they get only informed about network changes when they're visible.

    Second option

    Another option would be to stick to you current code and hold the reference of the Broadcast receiver somewhere centrally, again a custom Application class would do the job.

    So your activities know where to find the receiver for registering and unregistering. But be aware that you have to find a place where you initiate the receiver. Also keep in mind that you have to handle the case where you application might be closed by Android because of low memory and restarted later, you'll then have to recreate your receiver.

    0 讨论(0)
提交回复
热议问题