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.