Do Messages block in Android
Im writing an app which loads data from a rest interface. for this task i use a service which gets called by the activitys. Those calls are based on the "Message". I do it like that because i thought that just sending a message does not result in a blocking of the UI thread (i used much of the RemoteService example code from the android docs). But it feels like if the UI thread ater sending a message still gets blocked (ui doesnt update until the programflow, caused by the message has stoped).
Am i getting something wrong about the whole idea of the message system 开发者_开发百科? do i need to start the service in a separate thread to get around this ?!
Sending messages with the use of Handlers is not blocking depending on what you do with it. If you're sending a message to a Service, then immediately sending an http request in the server, then it will block. If you send a message, then have the service simply post a notification in the action bar, then it won't block.
Services run on the main UI thread. They do not run in the background, so anything you do in the Service will run on the UI thread and can block it if the Service does a lot of work.
Message
is processed by thread that is bound to Handler
you used to send message. If you created Handler
from UI thread, then your messages are processed in UI thread. You can use HandlerThread
or you can use IntentService
.
HandlerThread
is thread that has its own looper and you can create new handler from it:
thread = new HandlerThread("worker");
thread.start();
handler = new Handler(thread.getLooper());
IntentService
has worker thread and every start command is processed from worker thread in onHandleIntent(Intent)
精彩评论