Handler

Handler是Android中用于线程间通信的组件,主要负责将子线程中的消息传递到主线程,以便更新UI。它包括sendEmptyMessage、sendMessage和obtainMessage等方法来发送消息,MessageQueue作为消息队列,Looper负责取出消息交给主线程。倒计时案例展示了Handler的实际应用,包括在UI线程创建Handler对象,子线程发送消息,主线程接收并处理消息的过程。

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

什么是Handler

今天刚刚接触了handler,Handler被翻译成句柄,换句话说就是一个主线程和子线程传递消息的中介,简单理解,Handler就是解决线程和线程之间的通信的。当我们需要在子线程处理耗时的操作,需要更新UI,就需要使用Handler来处理,因为子线程不能做更新UI的操作。Handler能很容易的把任务传入主线程。

组成

sendEmptyMessage():发送消息
sendMessage:发送消息
obtainMessage:获得Message对象

重点原理

  • 子线程通过与主线程通信来更新UI
  • 主线程(UI线程)不允许进行耗时操作,所以耗时操作都在子线程进行

代码展示:按钮监听,文字框接收内容

downloadbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        downloadtips.setText("下载完成");

Looper和MessageQueue(工作机制)

Handler的消息处理

  • MessageQueue:消息队列(子线程有顺序的发送信息给主线程的聚集地)

  • Looper:将子线程发送的消息从聚集地取出送给主线程的角色

如何使用Handleder

  • 在UI创建Handler匿名内部类对象
private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
  • 在子线程中发送消息
 new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            Thread.sleep(5000);
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                       Message message=handler.obtainMessage();//创建message对象
                        message.what=1;
                        message.arg1=2;
                        message.obj="Hello";
                        handler.sendMessage(message);
                    }
                }
  • 在Handle中捕获消息
 super.handleMessage(msg);
            int arg1=msg.arg1;
            String info= (String) msg.obj;

            if (msg.what==1){
                downloadtips.setText("下载完成"+info+arg1);
            }

什么是Message

Message对象

  • what:int类型的消息码,接收方用来识别是什么消息
  • arg1:int类型,传递整型数字
  • obj:object类型,将消息发送给指定的Handle对象
 Message message=handler.obtainMessage();//创建message对象
                            message.what=1;
                            message.arg1=2;
                            message.obj="Hello";
                            handler.sendMessage(message);
 int arg1=msg.arg1;
            String info= (String) msg.obj;

            if (msg.what==1){
                downloadtips.setText("下载完成"+info+arg1);
            }

倒计时案例举例(附代码和效果图)

步骤详解

  • 绑定ID,按钮设置监听
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
time=Integer.parseInt(editText.getText().toString());//将字符串转换成整型
  • 在UI创建Handle对象
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
  • 在子线程发送消息
  • 设置倒计时
 new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for(int i=time;i>=0;i--){
                            //更新UI
                            handler.sendEmptyMessage(i);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }).start();
  • 主线程接收消息
textView.setText(msg.what+"");

视图代码演示

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.homework.activity.handlerdemo.ActivityDaojishi">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="设置时间"/>
        <EditText
            android:id="@+id/time_t"
            android:layout_width="wrap_content"
            android:layout_height="50dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="秒"/>
    </LinearLayout>

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="倒计时:"/>

        <TextView
            android:id="@+id/daojishi_t"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <Button
        android:id="@+id/start_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="开始计时"/>
</LinearLayout>

效果图演示
初始页面
第二张
第三张
倒计时结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值