关于Handler技术

来源:互联网 发布:灯火阑珊网络电视 编辑:程序博客网 时间:2024/06/08 17:50
android里面对于异步消息的处理,提供了一套Handler的实现方案。Handler有很多适宜的应用和微妙之处,使它在和Thread以及 Service等一起使用的时候达到很好的效果。
一、Handler与Thread的区别
默认情况下Handler与其创建者处于同一线程,如果Handler里面做耗时的动作,调用者线程会阻塞。
Android UI操作不是线程安全的,并且这些操作必须在UI线程中执行。

Android提供了几种基本的可以在其他线程中处理UI操作的方案,包括Activity 的runOnUiThread(Runnable),View的post以及1.5版本的工具类AsyncTask等方案都采用Handler,
Handler的post对线程的处理也不是真正start一个新的线程,而是直接调用了线程的run方法,这正是google煞费苦心搞一套Handler的用意。
public final boolean post (Runnable r)
Since: API Level 1

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
Parameters
r     The Runnable that will be executed.
Returns

    * Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. 

注:post (Runnable r)方法就是让Handler绑定的线程运行Runnable r的run方法。【post方法应该是非阻塞】
二 、  Handler对于Message的处理不是并发的
一个Looper 只有处理完一条Message才会读取下一条,所以消息的处理是阻塞形式的。但是如果用不同的Looper则能达到并发的目的。Service 中,onStart的执行也是阻塞的。如果一个startService在onStart执行完成之前,再次条用startService也会阻塞。
如果希望能尽快的执行onStart则可以在onStart中使用handler,因为Message的send是非阻塞的。
如果要是不同消息的处理也是并发的,则可以用不同的Looper实例化多个Handler。
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView label=(TextView)findViewById (R.id.lable1);
        Button button = (Button)findViewById(R.id.Button01);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                long timeStart=System.currentTimeMillis();
                /*Message的send是非阻塞的。[比如Handler的sendMessage()及Message的sendToTarget]
                但是handleMessage方法默认是绑在当前线程(Handler与调用者处于同一线程),他是阻塞的。
                */

                sendMessage();
                long time=System.currentTimeMillis();
                long len=time-timeStart;
                Log.i("hubin","time0:"+len);
                
                timeStart=System.currentTimeMillis();
                sendMessageWithLooper();//给让Handler绑定一个非当前线程,就可让handleMessage方法不阻塞当前线程了哦。
                time=System.currentTimeMillis();
                len=time-timeStart;
                Log.i("hubin","time1:"+len);               
                // Perform action on click
                Intent intent = new Intent("android.intent.action.Hello2");
               startActivityForResult(intent, 1);
            }
        });
        Log.v(TAG,TAGSUB+"onCreate");
    }
    //给让Handler绑定到当前线程(调用线程)
    public void sendMessage() {  
        MHandler mHandler = new MHandler();  
        /*这样创建Message要快。
        【参照文档它应该是从全局的一个缓冲中取个Message】
        【应该使用的就是liunx创建(构造)频繁使用对象那种技术】
        */

        Message msg = mHandler.obtainMessage();  
        msg.sendToTarget();  
     }  
     //给让Handler绑定一个新线程
     public void sendMessageWithLooper() {  
        HandlerThread ht = new HandlerThread("Rintail");  
        ht.start();  
        MHandler mHandler = new MHandler(ht.getLooper());  
        Message msg = mHandler.obtainMessage();  
        msg.sendToTarget();  
     }  
     
     class MHandler extends Handler {  
        public MHandler() {  
        }  
         public MHandler(Looper l) {  
          super(l);  
        }  
     
        @Override  
        public void handleMessage(Message msg) {  
          Log.d(TAG, "first");
          int i=100000;
          while (i>0) { 
              i--;
              int ii=i+i;
              Log.i(TAG,""+i);
          }  
          Log.d(TAG, "second");  
        }  
     }; 
  向Handler对象发送类似new Message ()形式的空Message可以达到清空Message的目的,这种做法与getLooper().quit()的做法是一样的。如果利用的资源较多,应及时清理。 
Handlder的post方法例:
public class  Hello extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mHandler = new Handler();
        Button button = (Button)findViewById(R.id.Button01); 
        OnClickListener listener=new OnClickListener(){
            @Override    
            public void onClick(View v) {     
                 Log.i("hubin","start"); 
                mHandler.post(mRunnable);
            }         
        };
        button.setOnClickListener(listener);
    }
    private Handler mHandler;
    public int speed=1000;
    public int cnt=0;
    private final Runnable mRunnable = new Runnable() {
        public void run() {
            cnt++;
            Log.i("hubin","run"+cnt);
                mHandler.postDelayed(this, speed);
        }
    };
}
关于默认情况下Handler与调用者处于同一线程的证据:
参考:文档关于Handler的描述
Class Overview
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. 
Each Handler instance is associated with a single thread and that thread's message queue.
默认构造函数描述
Handler()
Default constructor associates this handler with the queue for the current thread.
原创粉丝点击