Android中Handler的使用

一、什么是Handler?

Handler是Android SDK中处理异步消息的核心类。
Handler的作用是让子线程通过UI线程通信来更新UI界面。

handler对象的常用方法

sendEmptyMessage():发送消息,消息内容是int型
sendMessage():发送消息,消息内容是Message型
obtainMessage():从消息中获得一个Message对象,sendMessage时发出此Message
Post():将Runnable对象放入线程队列,不建议使用,post方法运行在UI线程中,耗时操作将阻塞UI线程
postDelayed():延迟多久后,将Runnable对象放入线程队列,不建议使用,post方法运行在UI线程中,耗时操作将阻塞UI线程

这里写图片描述
在整个程序中,主线程有且只能有一个,而子线程却可以有很多,而handler就是接收这些子线程传来信息来更新UI界面的。

二、Looper和MessageQueue

一个子线程的发展都要经历以下几个过程
这里写图片描述

Looper是handler接受消息中的转换器,而MessageQueue是其中的消息队列。

Looper:

1、在Android中创建出的普通县城默认是没有消息循环的,run方法执行完毕,线程也就结束了。
2、如果让线程不停地循环工作时,可以使用Looper,将普通线程变成循环工作线程。

MessageQueue:

1、当创建Looper时,将会自动创建MessageQueue。
2、一个线程中只会存在一个Looper和一个MessageQueue。
3、当MessageQueue中有消息时,Looper将从MessageQueue取出消息。

三、Message

Message类用于存放消息中的数据,该类通常与Handler类配合使用
Message对象:消息对象,子线程将需要传递到UI线程的信息放入Message对象中,Message对象可以通过Handler对象的obtainMessage方法获得。

Message对象常用属性

1.what属性:int类型的消息码,接收方用来识别是什么消息
2.arg1,arg2属性:int类型,如果传递的消息仅仅是整形数字,可以将数字赋给arg1或arg2
3. obj属性:Object类型,如果传递的消息是String或任意类型时,可将数据赋给obj属性
4.sendToTarget属性:将消息发送给制定的Handler对象

四、使用Handler的步骤

  1. 在UI线程中创建Handler匿名内部类对象;
  2. 在匿名内部类中重写handlerMessage方法;
  3. 在UI线程中启动子线程;
  4. 在线程中获得Message对象;
  5. 将需要传递的数据赋值的Message对象中;
  6. 通过Handler对象的sendMessage方法发送消息到消息队列;
  7. 在handlerMessage方法中获取消息。

五、运用Handler的实例——实现倒计时

要实现的倒计时如下效果图所示:

这里写图片描述
代码如下所示:
xml布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.lenovo.liu.handledemo.Main2Activity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="设计时间"
            android:textSize="25sp" />

        <EditText
            android:id="@+id/count_edit"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            //运用EditTexthint属性给出提示语
            android:hint="请输入倒计时间"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="秒"
            android:textSize="25sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/count_text"
            android:layout_width="120dp"
            android:layout_height="60dp"
            android:text="倒计时:"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/down_text"
            android:layout_width="40dp"
            android:layout_height="60dp"
            android:textSize="25sp" />
    </LinearLayout>

    <Button
        android:id="@+id/count_btn"
        android:layout_width="180dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:text="开始计时"
        android:textSize="20sp" />
</LinearLayout>

MainActivity中代码如下所示:

public class MainActivity  extends AppCompatActivity {
    //定义各种属性
    private Button countBtn;
    private TextView downTxt;
    private EditText countEdit;
    //定义一个整形num,方便将字符串转变为整型
    private int num;
    //创建Handler 
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
        //判断是否为what属性中的值,若是就输出
            if (msg.what==1){
                downTxt.setText(msg.arg1+"");
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        bindID();//绑定ID
        //创建监听事件
        countBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num=Integer.parseInt(countEdit.getText().toString());//将字符串转换成整型
               // 创建子线程
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //运用for循环来输出数值
                        for(int i=num;i>=0;i--){
                            try {
                                Thread.sleep(1000);//每隔3一秒休息一次
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //获取Message对象
                            Message  message=handler.obtainMessage();
                            // 将需要传递的数据赋值的Message对象中
                            message.what=1;
                            message.arg1=i;
                            //通过Handler对象的sendMessage方法发送消息到消息队列
                            handler.sendMessage(message);
                        }

                    }
                }).start();//启动子线程
            }
        });
    }
    //绑定ID所创建的类
    private void bindID() {
        countBtn=findViewById(R.id.count_btn);
        downTxt=findViewById(R.id.down_text);
        countEdit=findViewById(R.id.count_edit);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值