You should use Handler.post()
whenever you want to do operations on the UI thread.
So let's say you want to change a TextView
's text in the callback. Because the callback is not running on the UI thread, you should use Handler.post()
.
In Android, as in many other UI frameworks, UI elements (widgets) can be only modified from UI thread.
Also note that the terms "UI thread" and "main thread" are often used interchangeably.
Edit: an example of the long-running task:
mHandler = new Handler();
new Thread(new Runnable() {
@Override
public void run () {
// Perform long-running task here
// (like audio buffering).
// You may want to update a progress
// bar every second, so use a handler:
mHandler.post(new Runnable() {
@Override
public void run () {
// make operation on the UI - for example
// on a progress bar.
}
});
}
}).start();
Of course, if the task you want to perform is really long and there is a risk that user might switch to some another app in the meantime, you should consider using a Service.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…