Reputation: 589
I'm baffled at the lack of documentation for this typical scenario. I have 4 activities in my Android app - A, B, C, and D. I register a WiFi P2p broadcast receiver in Activity A. Once connected, the user can switch between Activities B, C and D, and may leave/kill the app by pressing the home button/killing from recent apps menu. Where should I unregister the broadcast receiver? In a single activity, you would register in the onResume() method and unregister in onPause(). What about multiple activities? It doesn't seem quite right to me that I may have to register and unregister for every activity.
Relevant code :
// helper class method called by Activity A by passing its context.
private void registerReceiver(Context context) {
context.registerReceiver(p2pBroadcastReceiver, p2pIntentFilter);
}
Sorry if this sounds too simple, please direct me to the right documentation/link!
Upvotes: 1
Views: 1637
Reputation: 680
As you start the activities B,C and D you can unregister broadcast receiver in the lifecycle call back methods in those respective activities B,C and D.
For example In your Activity B you can unregister the broadcast receiver in the onPause method of Activity B
public class MyActivity extends Activity
{
private final BroadcastReceiver mybroadcast = new SmsBR();
public void onPause()
{
super.onPause();
unregisterReceiver(mybroadcast);
}
}
The Android Framework will still call all the lifecycle callback methods even if the application gets killed by system or the user. So if you unregister in onPause() it will get called when activity goes to background or gets killed.
Upvotes: 1