强强笔记之android Handler 简解

来源:互联网 发布:淘宝网电动车 编辑:程序博客网 时间:2024/04/29 04:28

andorid 的Handler是一个非常有用的机制,但通过源码,我们可以发现Handler机制其实非常复杂,对于初学者(例如我)来说,看源码或是看那些关于Handler非常详细的文章会容易搞混自己,所以这是一篇关于Handler的简解,主要是想让读者理解Handler,在接下来我会陆续发一些Handler的详解。

首先我们来看一下官方的api:
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. 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.

从这段话我们可知:Handler是一个在不同线程里发送和处理信息的机制,也就是在不同线程里充当通讯兵的角色。

首先来看一下简单的布局,这里布局代码就不贴上了:
这里写图片描述
我们要想点击按钮改变textview的文字(Hello World),我们初学者想到的一般是:

TextView  textView=(TextView)findViewById(R.id.textView);public void HandlerClick(View v) {             new Thread(new Runnable() {            @Override            public void run() {                textView.setText("你想改啥就改啥");            }        }).start();       }

但是通过运行我们可以发现—–运行错误!!

这是为什么呢?这就关系到安卓的多线程问题了,安卓是不允许在ui线程之外访问ui工具包的,我们可以这样想,android中各自的线程都是独立的,textview在主线程中,自然轮不到其他线程擅自更改,你想要改只能建议我来改,改不改还得看我心情!!那么是通过一个怎样的机制建议我改一下textview呢?相信大家都猜出了—-Handler!!

贴一下修改之后完整的代码:

package com.example.hellotest;import android.app.Activity;import android.os.Handler;import android.os.Message;import android.os.Bundle;import android.view.View;import android.widget.TextView;public class MainActivity extends Activity {    TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView=(TextView)findViewById(R.id.textView);    }    public void HandlerClick(View v) {         new Thread(new Runnable() {            @Override            public void run() {                handler.sendEmptyMessage(100);            }        }).start();    }   Handler handler=new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            switch (msg.what) {                case 100:                    textView.setText("你想改啥就改啥");                    break;            }        }    };}

因为这是一篇简解,所以我只简单介绍一些上述代码,详细的欢迎看我的下一篇关于Handler的博客。

 handler.sendEmptyMessage(100);

这个方法传递信息,将100传到主线程中(100只是随便写的数字,任何int类型数字都可以传递),要想传递字符串或者其他类型的数据也可以通过不同的方法传递

  public void handleMessage(Message msg){}

这个方法是接收信息,我们姑且认为msg.what 是接收整型数据的吧,细心的你或许发现了还有msg.obj,msg.arg 等接收不同数据的代码,这里留到下一篇在细细解读。

0 0