Issue
I have extended the Application class in my app. In that class, I have a BroadcastReceiver that waits for Connectivity changes. If complete connectivity is lost, I am displaying a specific activity. However, if the app is not "in focus" (not in the foreground), I don't want to display that activity.
However, the Application class does not have an onPause or onResume method. How can I display this activity ONLY if the app is running? Do I have to have a BroadcastReceiver in all my Acitivities (there's quite a few of them, and I can't create an extended Activity for all of them since they extend different Activity classes (Activity, ListActivity, FragmentActivity, etc). Is it possible to only have one BroadcastReceiver where action is taken if and only if one of the app's Activities is in the foreground?
Solution
I'd say that registering BroadcastReceivers in your custom Application class is an anti-pattern. E.g., when do you unregister that receiver? As you mentioned, the Application class lacks the lifecycle callbacks an Activity has (at least most of them).
In your case, I'd register the Receiver that handles connectivity changes dynamically, in all of your Activities in the onResume() callback, and unregister them in the onPause() callback. It's quite possible, that all of your Activities could extend the FragmentActivity: ListAcitivity is just a helper class, you could easily handle all the list-related stuff on your own, and FragmentActivity just extends the basic Activity class.
So I recommend creating a custom base class for your Activities that handles the Receiver registration, which extends FragmentActivity. All your conrete Activity classes should extend this base class.
Answered By - Zsombor Erdődy-Nagy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.