admin 管理员组文章数量: 887021
Handler
先看一下执行结果,只是简单的输出但是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 [html] view plain copy print ?- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns: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>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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类 [java] view plain copy print ?
- 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(){
- @Override
- public void run() {
- // TODO Auto-generated method stub
- System.out.println("updateThread");
- handler.postDelayed(updateThread, 3000);//3秒之后把updateThread对象加入到线程消息队列中
- }
- };
- class ListenerS implements OnClickListener{
- @Override
- public void onClick(View arg0) {
- // TODO Auto-generated method stub
- handler.post(updateThread);//把updateThread对象加入到线程消息队列中
- }
- }
- class ListenerE implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- handler.removeCallbacks(updateThread);
- }
- }
- }
之前学习了handler的简单用法,如果还不知道handler是什么,可以看一下点击打开链接。这次深入一下,还是一样,先来看一下执行的效果
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android=""
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ProgressBar
- android:id="@+id/bar"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyleHorizontal"
- android:visibility="gone"
- />
- <Button
- android:id="@+id/btn"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="start"
- />
- </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">
<ProgressBar android:id="@+id/bar"android:layout_width="fill_parent" android:layout_height="wrap_content"style="?android:attr/progressBarStyleHorizontal"android:visibility="gone"/>
<Button android:id="@+id/btn"android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="start"/>
</LinearLayout>
activity类
[java] view plain copy print ?- package com.handler;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ProgressBar;
- import android.widget.Toast;
- public class progressHandler extends Activity {
- /** Called when the activity is first created. */
- private ProgressBar bar = null;
- private Button btn = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- bar = (ProgressBar)findViewById(R.id.bar);
- btn = (Button)findViewById(R.id.btn);
- btn.setOnClickListener(new MyListener());
- }
- class MyListener implements OnClickListener{
- @Override
- public void onClick(View arg0) {//第一步,触发button事件,把线程对象updateThread 添加到线程消息队列中
- // TODO Auto-generated method stub
- bar.setVisibility(View.VISIBLE);
- handler.post(updateThread);
- }
- }
- Handler handler = new Handler(){
- @Override
- public void handleMessage(Message msg) {//第五步,处理子线程发过来的消息
- // TODO Auto-generated method stub
- super.handleMessage(msg);
- bar.setProgress(msg.arg1);
- handler.post(updateThread);//继续调用子线程
- }
- };
- Runnable updateThread = new Runnable(){
- int i = 0;
- @Override
- public void run() {//第二步,启动线程
- // TODO Auto-generated method stub
- System.out.println("begin a thread");
- i += 10;
- Message msg = handler.obtainMessage();//第三步,从消息池中返回一个消息
- msg.arg1 = i;
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- handler.sendMessage(msg);//第四步,从子线程发送消息给主线程
- if(i==100){//第五步,判断i的值(由于handler是异步处理消息,所以同时会处理子线程发送给主线程的消息)
- handler.removeCallbacks(updateThread);
- bar.setVisibility(View.GONE);
- Toast.makeText(progressHandler.this, "你个SB!", Toast.LENGTH_LONG).show();
- }
- }
- };
- }
在handler(二)中点击打开链接,我们说handler是开启了另外一个线程,而且看代码的话确实是这样,实现了runnable接口,这在java中就是开启了一个线程,但是情况中的是这样吗?我们不妨来做个试验,如下
[java] view plain copy print ?
- <SPAN style="FONT-SIZE: 14px">package com.handlerThread;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- public class handlerThread extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Handler handler = new Handler();
- handler.post(r);
- System.out.println("activity线程ID:"+Thread.currentThread().getId());
- System.out.println("activity线程name:"+Thread.currentThread().getName());
- }
- Runnable r = new Runnable(){
- @Override
- public void run() {
- // TODO Auto-generated method stub
- System.out.println("handler线程ID:"+Thread.currentThread().getId());
- System.out.println("handler线程name:"+Thread.currentThread().getName());
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
- }</SPAN>
<span style="font-size:14px;">package com.handlerThread;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;public class handlerThread extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Handler handler = new Handler();handler.post(r);System.out.println("activity线程ID:"+Thread.currentThread().getId());System.out.println("activity线程name:"+Thread.currentThread().getName());}Runnable r = new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("handler线程ID:"+Thread.currentThread().getId());System.out.println("handler线程name:"+Thread.currentThread().getName());try {Thread.sleep(3000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};
}</span>
运行结果
其实,当我看到这里的时候也不敢相信,但是事实就是这样,handler没有重新开启一个线程,而是跟activity在同一个线程里,但是这种写法也就非常接近java的标准线程的写法了,难怪会误导人,如下是java的标准线程写法。
- <SPAN style="FONT-SIZE: 14px">package com.handlerThread;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- public class handlerThread extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // Handler handler = new Handler();
- // handler.post(r);
- Thread t = new Thread(r);
- t.start();
- System.out.println("activity线程ID:"+Thread.currentThread().getId());
- System.out.println("activity线程name:"+Thread.currentThread().getName());
- }
- Runnable r = new Runnable(){
- @Override
- public void run() {
- // TODO Auto-generated method stub
- System.out.println("handler线程ID:"+Thread.currentThread().getId());
- System.out.println("handler线程name:"+Thread.currentThread().getName());
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
- }</SPAN>
<span style="font-size:14px;">package com.handlerThread;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;public class handlerThread extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// Handler handler = new Handler();
// handler.post(r);Thread t = new Thread(r);t.start();System.out.println("activity线程ID:"+Thread.currentThread().getId());System.out.println("activity线程name:"+Thread.currentThread().getName());}Runnable r = new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("handler线程ID:"+Thread.currentThread().getId());System.out.println("handler线程name:"+Thread.currentThread().getName());try {Thread.sleep(3000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};
}</span>
运行结果如下:
这里就才是我们这种想要的结果,两者比较我们就会发现,handler虽然实现了runnable接口,但是却并没有启动一个线程,而是直接调用run方法。那andriod为什么要这样设计呢,既然不启动新的线程,为什么还要多此一举来实现runnable接口呢,我们继续探讨,下次再说。
在handler(三)中点击打开链接,我们知道普通的handler类是没有实现多线程的,在android中的handler要实现多线程,可以使用HandlerThread这个类,如下所示
[java] view plain copy print ?- package com.handlerThread;
- 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 handlerThread2 extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- System.out.println("activity线程ID:"+Thread.currentThread().getId());
- HandlerThread handlerThread = new HandlerThread("handlerThread");
- handlerThread.start();
- MyHandler handler = new MyHandler(handlerThread.getLooper());
- Message msg = handler.obtainMessage();
- msg.sendToTarget();
- }
- class MyHandler extends Handler {
- public MyHandler() {
- super();
- // TODO Auto-generated constructor stub
- }
- public MyHandler(Looper looper) {
- super(looper);
- // TODO Auto-generated constructor stub
- }
- @Override
- public void handleMessage(Message msg) {
- // TODO Auto-generated method stub
- super.handleMessage(msg);
- System.out.println("handler线程ID:"+Thread.currentThread().getId());
- }
- }
- }
package com.handlerThread;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 handlerThread2 extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.main);System.out.println("activity线程ID:"+Thread.currentThread().getId());HandlerThread handlerThread = new HandlerThread("handlerThread");handlerThread.start();MyHandler handler = new MyHandler(handlerThread.getLooper());Message msg = handler.obtainMessage();msg.sendToTarget();}class MyHandler extends Handler {public MyHandler() {super();// TODO Auto-generated constructor stub}public MyHandler(Looper looper) {super(looper);// TODO Auto-generated constructor stub}@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);System.out.println("handler线程ID:"+Thread.currentThread().getId());}}}
运行结果:
由此才可以说handler实现了真正意义上的多线程。
在上面的程序中我们看到有个新知识looper,那么什么是looper呢,如下是官方的解释
大概的意思就是说,looper是用来循环获取消息的,那么整个流程就可以看作是handler往消息队列中添加消息,looper再循环获取这些消息。
本文标签: Handler
版权声明:本文标题:Handler 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1686969417h51735.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论