android -- Looper.prepare()和Looper.loop() —深入版

本文详细解析了Android中Looper和Handler的工作原理,包括Looper如何为线程创建消息循环、Handler如何与Looper交互发送和处理消息,以及如何利用Looper和Handler实现主线程与子线程之间的消息传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android中的Looper类,是用来封装消息循环和消息队列的一个类,用于在android线程中进行消息处理。handler其实可以看做是一个工具类,用来向消息队列中插入消息的。


(1) Looper类用来为一个线程开启一个消息循环。 默认情况下android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环。) Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。


(2) 通常是通过Handler对象来与Looper进行交互的。Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。 默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,Handler在主线程中定义,那么它是与主线程的Looper绑定。 mainHandler = new Handler() 等价于new Handler(Looper.myLooper()). Looper.myLooper():获取当前进程的looper对象,类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。


(3) 在非主线程中直接new Handler() 会报如下的错误: E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。


(4) Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。


注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。
(5) 基于以上知识,可实现主线程给子线程(非主线程)发送消息。
把下面例子中的mHandler声明成类成员,在主线程通过mHandler发送消息即可。 Android官方文档中Looper的介绍: Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.

This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.


[java] view plain copy
  1. classLooperThreadextendsThread
  2. {
  3. publicHandlermHandler;
  4. publicvoidrun()
  5. {
  6. Looper.prepare();
  7. mHandler=newHandler()
  8. {
  9. publicvoidhandleMessage(Messagemsg)
  10. {
  11. //processincomingmessageshere
  12. }
  13. };
  14. Looper.loop();
  15. }

如果线程中使用Looper.prepare()和Looper.loop()创建了消息队列就可以让消息处理在该线程中完成


android HandlerThread使用小例

之前研究过handler 和 looper 消息队列,不过android里的handler不是另外开启线程来执行的,还是在主UI线程中,如果想另启线程的话需要用到HandlerThread来实现。在使用HandlerThread的时候需要实现CallBack接口以重写handlerMessage方法,在handlerMessage方法中来处理自己的逻辑。下来给出一个小例子程序。

layout文件很简单,就一个按钮来启动HanlderTread线程

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <TextView
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="@string/hello"/>
  10. <Button
  11. android:id="@+id/handlerThreadBtn"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="startHandlerThread"/>
  15. </LinearLayout>

Activity代码如下:

[java] view plain copy
  1. packagecom.tayue;
  2. importandroid.app.Activity;
  3. importandroid.os.Bundle;
  4. importandroid.os.Handler;
  5. importandroid.os.Handler.Callback;
  6. importandroid.os.HandlerThread;
  7. importandroid.os.Message;
  8. importandroid.view.View;
  9. importandroid.view.View.OnClickListener;
  10. importandroid.widget.Button;
  11. /**
  12. *
  13. *@authorxionglei
  14. *
  15. */
  16. publicclassTestHandlerActivityextendsActivityimplementsOnClickListener{
  17. publicButtonhandlerThreadBTN;
  18. MyHandlerThreadhandlerThread;
  19. Handlerhandler;
  20. /**Calledwhentheactivityisfirstcreated.*/
  21. @Override
  22. publicvoidonCreate(BundlesavedInstanceState){
  23. super.onCreate(savedInstanceState);
  24. //打印UI线程的名称
  25. System.out.println("onCreateCurrentThread="+Thread.currentThread().getName());
  26. setContentView(R.layout.main);
  27. handlerThreadBTN=(Button)findViewById(R.id.handlerThreadBtn);
  28. handlerThreadBTN.setOnClickListener(this);
  29. handlerThread=newMyHandlerThread("myHanler");
  30. handlerThread.start();
  31. //注意:这里必须用到handler的这个构造器,因为需要把callback传进去,从而使自己的HandlerThread的handlerMessage来替换掉Handler原生的handlerThread
  32. handler=newHandler(handlerThread.getLooper(),handlerThread);
  33. }
  34. @Override
  35. publicvoidonClick(Viewv){
  36. //点击按钮后来开启线程
  37. handler.sendEmptyMessage(1);
  38. }
  39. privateclassMyHandlerThreadextendsHandlerThreadimplementsCallback{
  40. publicMyHandlerThread(Stringname){
  41. super(name);
  42. }
  43. @Override
  44. publicbooleanhandleMessage(Messagemsg){
  45. //打印线程的名称
  46. System.out.println("handleMessageCurrentThread="+Thread.currentThread().getName());
  47. returntrue;
  48. }
  49. }
  50. }

点击按钮,打印的日志如下(这里点击了3次) 07-06 09:32:48.776: I/System.out(780): onCreate CurrentThread = main 07-06 09:32:55.076: I/System.out(780): handleMessage CurrentThread = myHanler 07-06 09:32:58.669: I/System.out(780): handleMessage CurrentThread = myHanler 07-06 09:33:03.476: I/System.out(780): handleMessage CurrentThread = myHanler

HandlerThread就这么简单。

当然 android自己也有异步线程的handler,就是AsyncTask,这个类就是封装了HandlerThread 和handler来实现异步多线程的操作的。

同样可以这样使用:

[java] view plain copy
  1. privatebooleaniscancel=false;//用户手动取消登录的标志位
  2. handlerThread=newHandlerThread("myHandlerThread");
  3. handlerThread.start();
  4. handler=newMyHandler(handlerThread.getLooper());
  5. //将要执行的线程对象添加到线程队列中
  6. handler.post(newRunnable(){
  7. @Override
  8. publicvoidrun(){
  9. Messagemessage=handler.obtainMessage();
  10. UserBeanuser=Bbs.getInstance().Login(username,password);//耗时任务
  11. Bundleb=newBundle();
  12. b.putSerializable("user",user);
  13. message.setData(b);
  14. message.sendToTarget();//或使用handler.sendMessage(message);
  15. }
  16. });
  17. classMyHandlerextendsHandler{
  18. publicMyHandler(Looperlooper){
  19. super(looper);
  20. }
  21. @Override
  22. publicvoidhandleMessage(Messagemsg){
  23. if(iscancel==false){
  24. //操作UI线程的代码
  25. Bundleb=msg.getData();
  26. UserBeanuser=(UserBean)b.get("user");
  27. ......
  28. }
  29. }
  30. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值