Difference between LocalBroadcastManager's sendBroadcast vs sendBroadcastSync?
from the CommonsWare Community archivesAt September 1, 2018, 6:41pm, hackzcorporation asked:
Getting Exception While Calling sendBroadcastSync() from background thread while its running fine when using sendBroadcast():
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:197)
at android.os.Handler.<init>(Handler.java:111)
at android.widget.Toast$TN.<init>(Toast.java:324)
at android.widget.Toast.<init>(Toast.java:91)
at android.widget.Toast.makeText(Toast.java:238)
at com.hackz.localbc.MainActivity$2.onReceive(MainActivity.java:52)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
at android.support.v4.content.LocalBroadcastManager.sendBroadcastSync(LocalBroadcastManager.java:290)
at com.hackz.localbc.MainActivity$SendText.run(MainActivity.java:65)
At September 1, 2018, 6:54pm, mmurphy replied:
sendBroadcastSync()
calls onReceive()
on the current thread, and you cannot raise a Toast
from a background thread. Use sendBroadcast()
instead, and onReceive()
will be called on the main application thread, from which you can display your Toast
. Or, do not display a Toast
in onReceive()
.
At September 1, 2018, 6:58pm, hackzcorporation replied:
Ohh …That’s the problem.
Official Docs says:
Like
sendBroadcast(Intent)
, but if there are any receivers for the Intent this function will block and immediately dispatch them before returning
I think it means that sendBroadcastSync(intent)
will always guarantee that onReceive() is called and after that it executes other code?
In other words sendBroadCast()
is asynchronous and sendBroadcastSync()
is synchronous!
I understand it right?
At September 1, 2018, 7:14pm, mmurphy replied:
Yes (assuming that there is at least one matching registered receiver).
In other words
sendBroadCast()
is asynchronous andsendBroadcastSync()
is synchronous!
Yes.