java - Two receivers of android LocalBroadcast, one in MainActivity, the other in a fragment -
in android app, registered receiver in mainactivity's oncreate
intentfilter mfilter = new intentfilter("action"); localbroadcastmanager.getinstance(this).registerreceiver(mreceiver, mfilter);
in onresume
new thread(new runnable() { @override public void run() { runonuithread(new runnable() { @override public void run() { intent = new intent("action"); localbroadcastmanager.getinstance(mainactivity.this).sendbroadcast(i); } }); } }).start();
frankly not sure why wanted use thread such (i copied code somewhere w/o digesting it).
this app supports viewpager, in associated fragment's oncreate
intentfilter mfilter = new intentfilter("action"); localbroadcastmanager.getinstance(getactivity()).registerreceiver(mreceiver, mfilter);
in both mainactivity , fragment class, 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 how localbroadcast works, expecting both receiver handlers run once broadcast emitted. instead noticed time receiver in mainactivity runs, in fragment class runs.
my hunch there thread part.
the reason behind such behavior can lifecycle of both activity fragment:
as per experience how methods called when have activity+fragment is:
- activity's
oncreate()
- activity's
onstart()
- activity's
onresume()
- fragment's
oncreateview()
- fragment's
onstart()
- fragment's
onresume()
explanation :
as fragment not initialized yet when broadcasting
onresume()
in activity not received @ first fragment receive activity. after once fragment initialized broadcast received fragment also.
Comments
Post a Comment