In a android app, I registered a receiver in MainActivity's onCreate
IntentFilter mFilter = new IntentFilter("Action");
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, mFilter);
In its onResume
new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent i = new Intent("Action");
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(i);
}
});
}
}).start();
Frankly I am not sure why we wanted to use a thread as such (I copied the code from somewhere w/o fully digesting it).
This app supports ViewPager, thus in its associated Fragment's onCreate
IntentFilter mFilter = new IntentFilter("Action");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, mFilter);
In both MainActivity and Fragment class, the receiver looks like:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
...
}
Only what's inside onReceive differs in both classes.
I don't know too much how LocalBroadcast works, I was expecting both receiver handlers would be run once the a broadcast is emitted. Instead I noticed most time only the receiver in MainActivity runs, occasionally that in the fragment class runs.
My hunch is that there is something to do with the thread part.
The reason behind Such behavior can be the Lifecycle of Both Activity as well as Fragment:
As per my experience how the methods get called when you have Activity+Fragment is:
onCreate()
onStart()
onResume()
onCreateView()
onStart()
onResume()
Explanation :
As your Fragment is not initialized yet when you are broadcasting from
onResume()
in Activity it could not be received at first by The Fragment but only receive by Activity. After that once the fragment is initialized the Broadcast will be received by the Fragment also.