使用Handler(Looper,Handler.Callback)構造函數(shù)并顯式指定循環(huán)器苫纤。
情景一:如果您希望代碼在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;
? ? }
});