使用Handler(Looper,Handler.Callback)构造函数并显式指定循环器。
情景一:如果您希望代码在main/UI thread上运行
Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
@Override public boolean handleMessage(@NonNullMessage message) {
// Your code
return true;
}
});
情景二:如果你想让代码在后台运行thread
// Create a background thread that has a Looper
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
// Using this handler to post tasks that running on a background thread.
Handler handler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
@Override public boolean handleMessage(@NonNullMessage message) {
// Your code
return true;
}
});
释放thread:handlerThread.quit();或者 handlerThread.quitSafely();
情景三:如果希望代码在后台thread上运行,并将结果返回main/UI thread
// Using this handler to post tasks that run on main/UI thread
Handler uiHandler = new Handler(Looper.getMainLooper());
// Create a background thread that has a LooperHandler
Thread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
// Using this handler to post task that run on a background
threadHandler handler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(@NonNullMessage message) {
// Execute the code or pass the result back to main/UI thread
uiHandler.post(new Runnable() {
@Override
public void run() {
}
});
return true;
}
});