Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to call sendBroadcast() from another thread?

Tags:

android

I have a service which creates a thread. This thread does some work and then calls sendBroadcast() on the Service. This means sendBroadcast() is called from the worker thread and not from the thread the service is running in.

Is this OK or should I make sure sendBroadcast() is called from the same thread as the Service (by using Handler and Runnable) ?

I found this on stackoverflow and Dianne Hackborns post.

According to the post it should be fine. The reason I ask is because the post is 2 years old and maybe something has changed. Also I could not find anything about this in the Android documentation.

like image 813
rve Avatar asked Jul 25 '12 19:07

rve


People also ask

Why should you avoid to run non UI code on the main thread?

All Android apps use a main thread to handle UI operations. Calling long-running operations from this main thread can lead to freezes and unresponsiveness. For example, if your app makes a network request from the main thread, your app's UI is frozen until it receives the network response.

What is sendBroadcast?

The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is called a Normal Broadcast. This is more efficient, but means that receivers cannot read results from other receivers, propagate data received from the broadcast, or abort the broadcast.

What is the use of BroadcastReceiver in Android?

Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.


1 Answers

That is fine. The Broadcast is handed to the Android OS and it is actually sent using OS threads so your thread that sends it does not matter.

like image 136
Kaediil Avatar answered Oct 18 '22 13:10

Kaediil