问题
I have a Handler, mHandler
, tied to the main thread. mHandler
resides in a Service
. Say I now post a Runnable
to mHandler
from the main thread like so:
public class SomeService extends Service {
// Handler is created on the main thread
// (and hence it is tied to the main thread)
private Handler mHandler = new Handler();
@Override
public void onDestroy() {
// onDestroy runs on the main thread
// Is the code in this Runnable processed right away?
mHandler.post(new Runnable() {
// (Some code statements that are to be run on the main thread)
...
});
super.onDestroy();
}
}
I know the example is a little silly as the Handler
is unnecessary. However, it is a good example for this question.
Now my questions are:
- Will the code statements in the
Runnable
be processed right away as the thread that posts theRunnable
is also the thread that is to process theRunnable
? Or does it work differently as theHandler
internally uses aMessageQueue
and hence there might beRunnable
s posted to theHandler
elsewhere (which arrive before myRunnable
)? - Moreover, is it possible that the statements will never run as the
post(Runnable r)
is an async call and henceonDestroy()
will finish and theService
will be killed by the system before theHandler
gets to run the code.
Thank you in advance.
回答1:
Since a
Service
does not imply a separate thread, your runnable will be posted at the end of the mainLooper
's queue, so yes, there may be messages/runnables scheduled before yours.Again, since
Service
does not imply a distinct thread, a call toonDestroy
does not mean that theHandler
's thread has been terminated. In this example, you are posting to the main looper, and that thread is active until the application process terminates.
来源:https://stackoverflow.com/questions/28618685/posting-to-handler-tied-to-current-thread