问题
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
Runnablebe processed right away as the thread that posts theRunnableis also the thread that is to process theRunnable? Or does it work differently as theHandlerinternally uses aMessageQueueand hence there might beRunnables posted to theHandlerelsewhere (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 theServicewill be killed by the system before theHandlergets to run the code.
Thank you in advance.
回答1:
Since a
Servicedoes 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
Servicedoes not imply a distinct thread, a call toonDestroydoes 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