multithreading - Android worker thread with its own Handler/Looper -


i want have worker thread can 1) send messages ui thread change things in gui, , 2) receive messages ui thread control worker thread's behavior.

the first part easy: create handler in ui thread , let worker thread send messages it. works charm. worker thread uses thread.sleep() perform efficient delay, wakes "do things", sends update ui thread's handler, , repeats.

the next part apparently difficult in android. worker thread must have looper create handler can receive messages, , looper.loop() blocking call means worker thread 100% committed running looper , can't other things doing ("do things", send update message, sleep, repeat).

this implies need third thread run looper worker thread, ridiculous. should possible have worker thread useful things, , process message if , when 1 arrives. yields efficient system minimum number of thread objects , minimal overhead. can't figure out how implement behavior in android.

so... how worker thread support handler , else useful? thanks!

the worker thread uses thread.sleep() perform efficient delay, wakes "do things", sends update ui thread's handler, , repeats.

it possible the right thing app, since decided not describe actual business problem, difficult tell. example, if writing email client, , needed control every 15 minutes check new email, proposed solution unreliable.

the next part apparently difficult in android

not especially.

the worker thread must have looper create handler can receive messages

only if want use handler that.

java, programming language, has been around long time. has many means of inter-thread communication. handler, looper, , handlerthread wrap around these offer 1 particular pattern. pattern not suitable scenarios, have noted. however, rest of java still exists, , many standard java classes part of android can take advantage of.

so, example, use linkedblockingqueue. have main application thread put commands onto queue. worker thread, rather using sleep(), use poll() timeout either pull event queue or wake after period of time.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -