Android中handler的作用与线程
jopen
10年前
Android handler 的主要用途根据官网上的解释,可以概括为两点:
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
也就是说handler保存了两个队列,一个消息队列,一个runnable队列,handler负责顺序一个一个执行两个队列里需要处理的元素。首先需要强调一下,handler并不是开辟了一个新的线程去执行,而是在其调用线程中,这个可以用以下代码去测试:
package com.relin.handler; import android.app.Activity; import android.os.Bundle; import android.os.Handler; public class AndroidHandlerActivity extends Activity { /** Called when the activity is first created. */ private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); handler.post(r); System.out.println("Activity-------->"+Thread.currentThread().getId()); System.out.println("Activityname----->"+Thread.currentThread().getName()); } Runnable r = new Runnable(){ @Override public void run(){ System.out.println("handler-------->"+Thread.currentThread().getId()); System.out.println("hanldername----->"+Thread.currentThread().getName()); try{ Thread.sleep(5000); }catch(Exception e){ } } }; }
上述代码首先定义了一个Runable对象,但是handler.post(r)并没有开辟新的线程,很容易发现,handler实际上使用的线程就是主线程。当然我们也可以用自定义一个线程,让handler在另一个线程中执行,这样主线程不会因为handler中有大量工作需要处理而进入阻塞状态:
package com.relin.bundle; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; public class AndroidBundleActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); System.out.println("activity----->" + Thread.currentThread().getId()); //由android系统内核提供,其中有一个looper专门用于处理消息队列 HandlerThread handlerThread = new HandlerThread("handler_thread"); //在使用getLooper之前,必须先调用start,不然looper是null handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper()); Message msg = myHandler.obtainMessage(); Bundle b = new Bundle(); b.putInt("age", 20); b.putString("name", "relin"); msg.setData(b); msg.sendToTarget(); } class MyHandler extends Handler{ public MyHandler(){ } public MyHandler(Looper looper){ super(looper); } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Bundle b = msg.getData(); int age = b.getInt("age"); String name = b.getString("name"); System.out.println("age is " + age + ", name is " + name); System.out.println("handler----->" + Thread.currentThread().getId()); } } }