Handler的作用与用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38998213/article/details/86500238

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);

        }
    };
1
2
3
4
5
6
7
8
从子线程中发出消息

                         Message message=handler.obtainMessage();
                           message.what=1;
                           message.arg1=i;
                           message.obj="倒计时:";
                           handler.sendMessage(message);
1
2
3
4
5
在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("完成");
            }
        }
    };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
5.Message的对象

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

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

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);
            }
1
2
3
4
5
6
7
8
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
在Activity中绑定好我们所创的控件Id ,为了实现按钮点击开始计时,我们还需要设置按钮的监听。

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

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

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

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

    private int num1;
    private String num;
1
2
 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;
        }

    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
之后再主线程中捕获消息,响应设置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("完成");
            }
        }
    };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
下面是全部代码:

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;
        }

    }
}
 

猜你喜欢

转载自blog.csdn.net/qq_38998213/article/details/86500238