Android Handler 原理分析及实例代码

发布时间 - 2026-01-10 22:51:28    点击率:

Android Handler 原理分析

Handler一个让无数android开发者头疼的东西,希望我今天这边文章能为您彻底根治这个问题

今天就为大家详细剖析下Handler的原理

Handler使用的原因

1.多线程更新Ui会导致UI界面错乱
2.如果加锁会导致性能下降
3.只在主线程去更新UI,轮询处理

Handler使用简介

其实关键方法就2个一个sendMessage,用来接收消息

另一个是handleMessage,用来处理接收到的消息

下面是我参考疯狂android讲义,写的一个子线程和主线程之间相互通信的demo

对原demo做了一定修改

public class MainActivity extends AppCompatActivity { 
  public final static String UPPER_NUM="upper_num"; 
  private EditText editText; 
  public jisuanThread jisuan; 
  public Handler mainhandler; 
  private TextView textView; 
  class jisuanThread extends Thread{ 
    public Handler mhandler; 
    @Override 
    public void run() { 
      Looper.prepare(); 
      final ArrayList<Integer> al=new ArrayList<>(); 
      mhandler=new Handler(){ 
        @Override 
        public void handleMessage(Message msg) { 
 
          if(msg.what==0x123){ 
            Bundle bundle=msg.getData(); 
            int up=bundle.getInt(UPPER_NUM); 
            outer: 
            for(int i=3;i<=up;i++){ 
              for(int j=2;j<=Math.sqrt(i);j++){ 
                if(i%j==0){ 
                  continue outer; 
                } 
              } 
              al.add(i); 
            } 
            Message message=new Message(); 
            message.what=0x124; 
            Bundle bundle1=new Bundle(); 
            bundle1.putIntegerArrayList("Result",al); 
            message.setData(bundle1); 
            mainhandler.sendMessage(message); 
          } 
        } 
      }; 
      Looper.loop(); 
    } 
  } 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    editText= (EditText) findViewById(R.id.et_num); 
    textView= (TextView) findViewById(R.id.tv_show); 
    jisuan=new jisuanThread(); 
    jisuan.start(); 
    mainhandler=new Handler(){ 
      @Override 
      public void handleMessage(Message msg) { 
        if(msg.what==0x124){ 
          Bundle bundle=new Bundle(); 
          bundle=msg.getData(); 
          ArrayList<Integer> al=bundle.getIntegerArrayList("Result"); 
          textView.setText(al.toString()); 
        } 
      } 
    }; 
    findViewById(R.id.bt_jisuan).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        Message message=new Message(); 
        message.what=0x123; 
        Bundle bundle=new Bundle(); 
        bundle.putInt(UPPER_NUM, Integer.parseInt(editText.getText().toString())); 
        message.setData(bundle); 
        jisuan.mhandler.sendMessage(message); 
      } 
    }); 
  } 
} 

Hanler和Looper,MessageQueue原理分析

1.Handler发送消息处理消息(一般都是将消息发送给自己),因为hanler在不同线程是可使用的

2.Looper管理MessageQueue

Looper.loop死循环,不断从MessageQueue取消息,如果有消息就处理消息,没有消息就阻塞

public static void loop() { 
    final Looper me = myLooper(); 
    if (me == null) { 
      throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 
    } 
    final MessageQueue queue = me.mQueue; 
    // Make sure the identity of this thread is that of the local process, 
    // and keep track of what that identity token actually is. 
    Binder.clearCallingIdentity(); 
    final long ident = Binder.clearCallingIdentity(); 
 
    for (;;) { 
      Message msg = queue.next(); // might block 
      if (msg == null) { 
        // No message indicates that the message queue is quitting. 
        return; 
      } 
      // This must be in a local variable, in case a UI event sets the logger 
      Printer logging = me.mLogging; 
      if (logging != null) { 
        logging.println(">>>>> Dispatching to " + msg.target + " " + 
            msg.callback + ": " + msg.what); 
      } 
      msg.target.dispatchMessage(msg); 
 
      if (logging != null) { 
        logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); 
      } 
      // Make sure that during the course of dispatching the 
      // identity of the thread wasn't corrupted. 
      final long newIdent = Binder.clearCallingIdentity(); 
      if (ident != newIdent) { 
        Log.wtf(TAG, "Thread identity changed from 0x" 
            + Long.toHexString(ident) + " to 0x" 
            + Long.toHexString(newIdent) + " while dispatching to " 
            + msg.target.getClass().getName() + " " 
            + msg.callback + " what=" + msg.what); 
      } 
 
      msg.recycleUnchecked(); 
    } 
  } 

这个是Looper.loop的源码,实质就是一个死循环,不断读取自己的MessQueue的消息

3.MessQueue一个消息队列,Handler发送的消息会添加到与自己内联的Looper的MessQueue中,受Looper管理

private Looper(boolean quitAllowed) { 
    mQueue = new MessageQueue(quitAllowed); 
    mThread = Thread.currentThread(); 
  } 

这个是Looper构造器,其中做了2个工作,

1.生成与自己关联的Message

2.绑定到当前线程

主线程在初始化的时候已经生成Looper,

其他线程如果想使用handler需要通过Looper.prepare()生成一个自己线程绑定的looper

这就是Looper.prepare()源码,其实质也是使用构造器生成一个looper

private static void prepare(boolean quitAllowed) { 
    if (sThreadLocal.get() != null) { 
      throw new RuntimeException("Only one Looper may be created per thread"); 
    } 
    sThreadLocal.set(new Looper(quitAllowed)); 
  } 

4.handler发送消息会将消息保存在自己相关联的Looper的MessageQueue中,那它是如何找到这个MessageQueue的呢

public Handler(Callback callback, boolean async) { 
    if (FIND_POTENTIAL_LEAKS) { 
      final Class<? extends Handler> klass = getClass(); 
      if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 
          (klass.getModifiers() & Modifier.STATIC) == 0) { 
        Log.w(TAG, "The following Handler class should be static or leaks might occur: " + 
          klass.getCanonicalName()); 
      } 
    } 
 
    mLooper = Looper.myLooper(); 
    if (mLooper == null) { 
      throw new RuntimeException( 
        "Can't create handler inside thread that has not called Looper.prepare()"); 
    } 
    mQueue = mLooper.mQueue; 
    mCallback = callback; 
    mAsynchronous = async; 
  } 

这个是Handler的构造方法,它会找到一个自己关联的一个Looper

public static Looper myLooper() { 
    return sThreadLocal.get(); 
  } 

没错,他们之间也是通过线程关联的,得到Looper之后自然就可以获得它的MessageQueue了

5.我们再看下handler如发送消息,又是如何在发送完消息后,回调HandlerMessage的

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { 
    msg.target = this; 
    if (mAsynchronous) { 
      msg.setAsynchronous(true); 
    } 
    return queue.enqueueMessage(msg, uptimeMillis); 
  } 

这个就是Handler发送消息的最终源码,可见就是将一个message添加到MessageQueue中,那为什么发送完消息又能及时回调handleMessage方法呢

大家请看上边那个loop方法,其中的for循环里面有一句话msg.target.dispatchMessage(msg);

public void dispatchMessage(Message msg) { 
    if (msg.callback != null) { 
      handleCallback(msg); 
    } else { 
      if (mCallback != null) { 
        if (mCallback.handleMessage(msg)) { 
          return; 
        } 
      } 
      handleMessage(msg); 
    } 
  } 

这就是这句话,看到了吧里面会调用hanlerMessage,一切都联系起来了吧

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


# Android  # Handler  # 原理分析  # 详解  # Android消息机制Handler的工作过程详解  # Android计时器的三种实现方式(Chronometer、Timer、handler)  # Android 消息机制以及handler的内存泄露  # Android Handler多线程详解  # Android 中Handler引起的内存泄露  # Android Handler 机制实现原理分析  # Android用HandlerThread模拟AsyncTask功能(ThreadTask)  # Android Handler消息派发机制源码分析  # Android使用Handler和Message更新UI  # 详解Android中Handler的实现原理  # 发送消息  # 这就是  # 绑定  # 回调  # 自己的  # 都是  # 有一  # 又是  # 为您  # 一切都  # 这个问题  # 它是  # 这句话  # 给自己  # 希望能  # 相关联  # 又能  # 只在  # 再看  # 句话 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Win11搜索不到蓝牙耳机怎么办 Win11蓝牙驱动更新修复【详解】  zabbix利用python脚本发送报警邮件的方法  Laravel路由怎么定义_Laravel核心路由系统完全入门指南  原生JS实现图片轮播切换效果  Laravel数据库迁移怎么用_Laravel Migration管理数据库结构的正确姿势  手机软键盘弹出时影响布局的解决方法  Win11怎么设置默认图片查看器_Windows11照片应用关联设置  googleplay官方入口在哪里_Google Play官方商店快速入口指南  惠州网站建设制作推广,惠州市华视达文化传媒有限公司怎么样?  北京网站制作公司哪家好一点,北京租房网站有哪些?  如何构建满足综合性能需求的优质建站方案?  Laravel怎么做数据加密_Laravel内置Crypt门面的加密与解密功能  Laravel N+1查询问题如何解决_Eloquent预加载(Eager Loading)优化数据库查询  Android利用动画实现背景逐渐变暗  怎么用AI帮你为初创公司进行市场定位分析?  悟空识字怎么关闭自动续费_悟空识字取消会员自动扣费步骤  php485函数参数是什么意思_php485各参数详细说明【介绍】  html5源代码发行怎么设置权限_访问权限控制方法与实践【指南】  如何在万网主机上快速搭建网站?  网站制作免费,什么网站能看正片电影?  创业网站制作流程,创业网站可靠吗?  如何在VPS电脑上快速搭建网站?  Python制作简易注册登录系统  如何做网站制作流程,*游戏网站怎么搭建?  Laravel如何使用Service Provider注册服务_Laravel服务提供者配置与加载  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  HTML5段落标签p和br怎么选_文本排版常用标签对比【解答】  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  如何用免费手机建站系统零基础打造专业网站?  Laravel的Blade指令怎么自定义_创建你自己的Laravel Blade Directives  Java遍历集合的三种方式  如何快速查询网站的真实建站时间?  JavaScript 输出显示内容(document.write、alert、innerHTML、console.log)  网站建设保证美观性,需要考虑的几点问题!  laravel怎么用DB facade执行原生SQL查询_laravel DB facade原生SQL执行方法  Laravel如何使用Facades(门面)及其工作原理_Laravel门面模式与底层机制  Windows10电脑怎么查看硬盘通电时间_Win10使用工具检测磁盘健康  Laravel如何实现图片防盗链功能_Laravel中间件验证Referer来源请求【方案】  千问怎样用提示词获取健康建议_千问健康类提示词注意事项【指南】  香港服务器网站搭建教程-电商部署、配置优化与安全稳定指南  Laravel如何生成URL和重定向?(路由助手函数)  手机网站制作平台,手机靓号代理商怎么制作属于自己的手机靓号网站?  网站制作大概多少钱一个,做一个平台网站大概多少钱?  如何在景安服务器上快速搭建个人网站?  Laravel如何创建自定义Facades?(详细步骤)  Python文件异常处理策略_健壮性说明【指导】  详解MySQL数据库的安装与密码配置  Laravel如何自定义错误页面(404, 500)?(代码示例)  Laravel辅助函数有哪些_Laravel Helpers常用助手函数大全  猎豹浏览器开发者工具怎么打开 猎豹浏览器F12调试工具使用【前端必备】