2

I have an application with several activities and I want to be notified when the phone goes online (doesn't matter which activity is the user in). I've found a Broadcast Receiver to do it, but I'd like to know if there is a way to declare this BroadcastReceiver only once, I want to avoid having to place the code in each activity (I have more than 20 activities!).

Thank you.

PX Developer
  • 8,065
  • 7
  • 42
  • 66

2 Answers2

2

Create a parent abstract class which extends Activity and define the broadcast receiver implementation there. Later, modify your activity classes to extend that parent class.

waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • Oh, I hadn't thought about that. What if I wanted to be notified even if the app is closed (no activity opened)? – PX Developer Sep 27 '12 at 10:17
  • Create a `boolean` flag (lets say **isVisible**) in your parent class and override `onStart` and `onStop` methods. In `onStart`, set the flag to `true` and in `onStop` set it to `false`. This will tell you if the activity is visible on screen or not. – waqaslam Sep 27 '12 at 10:32
  • Another approach that has been mentioned before is using a singleton class. But just keep in mind the caveats of multi-threading. It all depends upon your situation. – Daniel Eagle Oct 13 '14 at 14:57
1

As in documentation, If we declares the broadcast receiver in manifest file then it automatically runs behind. Thing is that now you need to handle the onReceive() method of the receiver. Another way is that you make a separate java class and import wherever you want.

Caution Continues
  • 743
  • 2
  • 10
  • 25