Looper
非主线程
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }
主线程
public static final void main(String[] args) { // other codes... // 创建主线程循环 Looper.prepareMainLooper(); if (sMainThreadHandler == null) { sMainThreadHandler = new Handler(); } ActivityThread thread = new ActivityThread(); thread.attach(false); // other codes... // 进入当前线程(此时是主线程)消息循环 Looper.loop(); // other codes... thread.detach(); // other codes... }
Android 非主线程hanlder
public class TestThread extends Thread { private Handler handler; private static final String TAG = "Test"; @Override public void run() { Log.i(TAG, "run().."); Looper.prepare(); handler = new Handler(Looper.myLooper()) { @Override public void handleMessage(Message msg) { Log.i(TAG, "msg:" + msg.what); } }; new Thread() { @Override public void run() { Log.i(TAG, "sub thread run().."); try { while (true) { Thread.sleep(4000); handler.sendEmptyMessage(1); } } catch (Exception e) { e.printStackTrace(); } } }.start(); Looper.loop(); } }

浙公网安备 33010602011771号