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:

  1. activity's oncreate()
  2. activity's onstart()
  3. activity's onresume()
  4. fragment's oncreateview()
  5. fragment's onstart()
  6. 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

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -