Android Handler和HandlerThread使用方法Handler的官方注释如下:A Handler allows you to send and proces
Android Handler和HandlerThread使用方法
Handler的官方注释如下:
A Handler allows you to send and process
Messageand Runnable objects associated with a thread’sMessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue.
Handler会关联一个单独的线程和消息队列。Handler默认关联主线程,虽然要提供Runnable参数 ,但默认是直接调用Runnable中的run()方法。也就是默认下会在主线程执行,如果在这里面的操作会有阻塞,界面也会卡住。如果要在其他线程执行,可以使用HandlerThread。
Handler使用方法: Handler handler = new Handler() { @Overridepublic void handleMessage(Message msg) {// 处理发送过来的消息Bundle b = msg.getData();System.out.println("msg:" + msg.arg1);System.out.println("msg:" + b.getString("name") + " - age:" + b.getInt("age"));super.handleMessage(msg);} }; Message msg = handler.obtainMessage(); msg.arg1 = 121; Bundle b = new Bundle(); b.putInt("age", 24); b.putString("name", "Fatkun"); msg.setData(b); msg.sendToTarget(); handler.post(r); } Runnable r = new Runnable() { public void run() {try { // 在这里只是睡一下Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();} }};HandlerThread使用方法://把上面创建Handler的代码Handler handler = new Handler() {...} //改为:HandlerThread thread = new HandlerThread("athread");thread.start(); //要把线程启动 Handler handler = new Handler(thread.getLooper()) {...}