Android开发之handler(一)

来源:互联网 发布:号码追逐软件 编辑:程序博客网 时间:2024/05/24 03:19

        先看一下执行结果,只是简单的输出

       但是handler到底是何方神圣呢,我们来看一下官方的解释:

         A Handler allows you to send and process Message and Runnable objects associated with a thread'sMessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

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是用来处理线程之间的消息的。详细的解释可以看一下下面这段话,是网上看到的,讲的非常好

Handler的定义:

  * 主要接受子线程发送的数据, 并用此数据配合主线程更新UI。当应用程序启动时,

  * Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说,

  * 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。

  * 如果此时需要一个耗时的操作,例如: 联网读取数据,或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,

  * 如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,会收到Android系统的一个错误提示 "强制关闭"。

  * 这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,Android主线程是线程不安全的,

  * 也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。这个时候,Handler就出现了,来解决这个复杂的问题 ,

  * 由于Handler运行在主线程中(UI线程中),它与子线程可以通过Message对象来传递数据,

  * 这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象(里面包含数据),把这些消息放入主线程队列中,配合主线程进行更新UI。

  * Handler一些特点:

  * Handler可以分发Message对象和Runnable对象到主线程中, 每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),

  * 它有两个作用: (1): 安排消息或Runnable 在某个主线程中某个地方执行, (2)安排一个动作在不同的线程中执行

  * Handler中分发消息的一些方法

  * post(Runnable)

  * postAtTime(Runnable,long)

  * postDelayed(Runnable,long)

  * sendEmptyMessage(int)

  * sendMessage(Message)

  * sendMessageAtTime(Message,long)

  * sendMessageDelayed(Message,long)

  * 以上post类方法允许你排列一个Runnable对象到主线程队列中,当需要在不同于主UI线程中执行则需要配合HandlerThread进行使用:

  * HandlerThread handlerThread = new HandlerThread("myHandlerThread");

  * handlerThread.start();

  * handler = new Handler(handlerThread.getLooper());* sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新.

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><Button android:text="@string/start" android:id="@+id/butS"android:layout_width="fill_parent" android:layout_height="wrap_content"></Button><Button android:text="@string/end" android:id="@+id/butE"android:layout_width="fill_parent" android:layout_height="wrap_content"></Button></LinearLayout>

activity类

package com.handler;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class handlerTest extends Activity {    /** Called when the activity is first created. */private Button butS,butE;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                butS = (Button)findViewById(R.id.butS);        butS.setOnClickListener(new ListenerS());        butE = (Button)findViewById(R.id.butE);        butE.setOnClickListener(new ListenerE());    }    Handler handler = new Handler();    Runnable updateThread = new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("updateThread");handler.postDelayed(updateThread, 3000);//3秒之后把updateThread对象加入到线程消息队列中}    };    class ListenerS implements OnClickListener{@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubhandler.post(updateThread);//把updateThread对象加入到线程消息队列中}        }    class ListenerE implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubhandler.removeCallbacks(updateThread);}    }}