也许大家创建Handler都不陌生,但是如果要在子线程创建Handler,大家未必都能正确,
在子线程中创建handler,要确保子线程有Looper,UI线程默认包含Looper
我们需要用到一个特殊类
HandlerThread
这个类可以轻松的创建子线程handler
创建步骤:
1: 创建一个HandlerThread,即创建一个包含Looper的线程
HandlerThread的构造函数有两个
public HandlerThread(String name) { super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; } /** * Constructs a HandlerThread. * @param name * @param priority The priority to run the thread at. The value supplied must be from * {@link android.os.Process} and not from java.lang.Thread. */ public HandlerThread(String name, int priority) { super(name); mPriority = priority; }
这里我们使用第一个就好:
HandlerThread handlerThread=new HandlerThread("xuan");
handlerThread.start();//创建HandlerThread后一定要记得start();
通过HandlerThread的getLooper方法可以获取Looper
Looper looper=handlerThread.getLooper();
通过Looper我们就可以创建子线程的handler了
Handlr handler=new Handler(looper);
通过该handler发送消息,就会在子线程执行;
提示:如果要handlerThread停止:handlerThread.quit();
完整测试代码:
HandlerThread hanlerThread = new HandlerThread("子线程"); hanlerThread.start(); final Handler handler = new Handler(hanlerThread.getLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.d("----->", "线程:" + Thread.currentThread().getName()); } }; findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler.sendEmptyMessage(100); } });
结果:
12-24 10:13:15.881 5024-5052/gitosctest.gitosc_studyproject D/----->: 线程:子线程