必威体育Betway必威体育官网
当前位置:首页 > IT技术

Handler的作用与用法

时间:2019-06-03 16:45:08来源:IT技术作者:seo实验室小编阅读:70次「手机版」
 

handler

1.什么是handler?

Handler是Android SDK来处理异步消息的核心类。

线程与主线程通过Handler来进行通信。子线程可以通过Handler来通知主线程进行UI更新。

2.什么是messagequeue和Looper

这里写图片描述

如图MessageQueue用来保存子线程从Handler所发送未处理的消息,Looper依次取出MessageQueue中的消息传递给主线程响应处理。

3.为什么使用handler,MessageQueue,Looper?

主线程无法进行时间比较繁长的任务,所以需要子线程进行处理,然而子线程无法进行UI的界面更新,所以我们需要使用handler来传递消息给主线程,让其完成UI的更新。由于主线程和子线程进行不同的时间工作,所要需要用MessageQueue来存放子线程的消息,Looper取出消息交给主线程响应。

4.使用handler的主要步骤

主要步骤分为三布:

1.首先创建好handler.

private  Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           super.handleMessage(msg);

        }
    };

从子线程中发出消息

                         Message message=handler.obtainMessage();
                           message.what=1;
                           message.arg1=i;
                           message.obj="倒计时:";
                           handler.sendMessage(message);

在handler中捕获所需消息,实现响应

  private  Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int arg1=msg.arg1;
            String info= (String) msg.obj;
            if (msg.what==1){
                textView.setText(info+arg1);
            }
            if (arg1==0){
                textView.setText("完成");
            }
        }
    };

5.Message的对象

  1. what属性:

    int类型,主线程用来识别子线程发来的是什么消息。

  2. arg1属性:

    int类型,如果传递的消息类型为int型,可以将数字赋给arg1,arg2。

  3. obj属性:

    Objectt类型,如果传递的消息是String或者其他,可以赋给obj。

                        message.what=1;//what属性
                           message.arg1=i;//arg属性
                           message.obj="倒计时:";//obj属性
                           handler.sendMessage(message);
 if (msg.what==1)//识别判断消息
 {
                textView.setText(info+arg1);
            }

6.使用Handler和线程制作简单的计时器

首先创建好Activity并完善好Activity的布局文件,做好响应的控件和ID

<?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.example.wang3.myapplication.ThreadActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="输入计时时间:"
    android:textSize="20sp"/>
    <EditText
        android:id="@+id/theradedtext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入数字"
        android:numeric="integer"
        />
</LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000"/>
    <TextView
        android:id="@+id/theradtext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="倒计时:**"
        android:textSize="20sp"
        android:gravity="center"/>
    <Button
        android:id="@+id/theradbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="开始计时"/>

</LinearLayout>

在Activity中绑定好我们所创的控件Id ,为了实现按钮点击开始计时,我们还需要设置按钮的监听。

 private Button button;
    private TextView textView;
    private EditText editText;
 private void blindID() {
        button=findViewById(R.id.theradbtn);
        textView=findViewById(R.id.theradtext);
        editText=findViewById(R.id.theradedtext);
        button.setOnClickListener(this);

    }

时间倒计时我们需要用子线程来通过Handler来传递时间的变化,主线程获取响应,所以要先创建好Handler

private  Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

                  }
    };

设置好监听事件,我们需要从EditText中获取所要设定的时间,所以创建int型来获取存放用户所输入的数字,将显示的Textview设置为倒计时+数字,利用for循环来改变数字,并创建一个新子线程来实现读秒,让子线程睡上一秒后发送新的信息。

    private int num1;
    private String num;
 public void onClick(View view) {
        switch (view.getId()){

            case R.id.theradbtn:
                num=editText.getText().toString();
                num1=Integer.parseInt(num);
                textView.setText("倒计时:"+num1);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                       for (int i=num1;i >=0;i--) {
                           try {
                               Thread.sleep(1000);//实现读秒
                           } catch (InterruptedException e) {
                               e.printstacktrace();
                           }
                           Message message=handler.obtainMessage();
                           message.what=1;
                           message.arg1=i;
                           message.obj="倒计时:";
                           handler.sendMessage(message);//发送信息

                       }
                    }
                }).start();
                break;
        }

    }

之后再主线程中捕获消息,响应设置TextView的更新,实现每隔一秒改变数字,完成一个计时的简单功能

   private  Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int arg1=msg.arg1;
            String info= (String) msg.obj;
            if (msg.what==1){
                textView.setText(info+arg1);
            }
            if (arg1==0){
                textView.setText("完成");
            }
        }
    };

下面是全部代码

package com.example.wang3.myapplication;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ThreadActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button;
    private TextView textView;
    private EditText editText;
    private int num1;
    private String num;
    private  Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int arg1=msg.arg1;
            String info= (String) msg.obj;
            if (msg.what==1){
                textView.setText(info+arg1);
            }
            if (arg1==0){
                textView.setText("完成");
            }
        }
    };

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


    }

    private void BlindID() {
        button=findViewById(R.id.theradbtn);
        textView=findViewById(R.id.theradtext);
        editText=findViewById(R.id.theradedtext);
        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){

            case R.id.theradbtn:
                num=editText.getText().toString();
                num1=Integer.parseInt(num);
                textView.setText("倒计时:"+num1);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                       for (int i=num1;i >=0;i--) {
                           try {
                               Thread.sleep(1000);
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }
                           Message message=handler.obtainMessage();
                           message.what=1;
                           message.arg1=i;
                           message.obj="倒计时:";
                           handler.sendMessage(message);

                       }
                    }
                }).start();
                break;
        }

    }
}

以及效果图:

这里写图片描述

相关阅读

HandlerThread 的使用及原理

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note tha

HandlerThread的应用场景

HandlerThread是什么? 它就是一个线程,一个实现了Handler通信机制的线程,也就是说不用我们再去实现Looper的一系列工作了。实现了这

Handler消息机制之深入理解Message.obtain()

前言:在我们日常开发工作中,难免经常会在线程间进行消息传递,而这个过程最常用的实现方式就是Handler消息机制。当然,这并不我们今天

HandlerThread(详细例子)

HandlerThread是什么 官方解释 Handy class for starting a new thread that has a looper. The looper can then be used to cre

为什么要用Handler

一、什么是handler? 注:线程分为主线程(主线程又叫UI线程,只能有一个主线程)和子线程(可以有多个)Handler只能在主线程里运行 handle

分享到:

栏目导航

推荐阅读

热门阅读