网络操作-02 Handler通信



 

 1.将要执行的消息和运行表安排为未来

2.将要在与您的线程不同的线程上执行的操作排成队列自己



MainActivity.java: 

package com.example.handlerproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView textview = (TextView) findViewById(R.id.textView);

        //创建Handler
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //处理消息
            Log.d(TAG, "handleMessage: " + msg.what);
            }

        };
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                textview.setText("imooc");
            }
        });
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="79dp"
        android:layout_height="33dp"
        android:text="Button"
        tools:layout_editor_absoluteX="49dp"
        tools:layout_editor_absoluteY="329dp" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java:

package com.example.handlerproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /**
         * UI线程
         */
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView textview = (TextView) findViewById(R.id.textView);

        //创建Handler
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                /**
                 * 主线程接到子线程发出来的消息,处理
                 */

                //处理消息
                Log.d(TAG, "handleMessage: " + msg.what);

                if(msg.what == 1001){
                    textview.setText("imooc");
                }
            }

        };

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                //有可能做大量耗时操作
                /**
                 * 子线程
                 */
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                        /**
                         * 通知UI更新
                         */

                        handler.sendEmptyMessage(1001);

                    }
                }).start();

            }
        });
    }
}

Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="79dp"
        android:layout_height="33dp"
        android:text="Button"
        tools:layout_editor_absoluteX="49dp"
        tools:layout_editor_absoluteY="329dp" />

</androidx.constraintlayout.widget.ConstraintLayout>



Handler实现倒计时并优化内存:

 1 package com.imooc.countdowntime;
 2 
 3 import android.os.Handler;
 4 import android.os.Message;
 5 import android.support.v7.app.AppCompatActivity;
 6 import android.os.Bundle;
 7 import android.widget.TextView;
 8 
 9 import java.lang.ref.WeakReference;
10 
11 public class MainActivity extends AppCompatActivity {
12 
13     /**
14      * 倒计时标记handle code
15      */
16     public  static  final  int COUNTDOWN_TIME_CODE = 100001;
17     /**
18      * 倒计时间隔
19      */
20     public  static  final  int  DELAY_MILLIS = 1000;
21     /**
22      * 倒计时最大值
23      */
24     public  static  final  int  MAX_COUNT = 10;
25 
26 
27     private TextView mCountdownTimeTextView;
28 
29 
30     @Override
31     protected void onCreate(Bundle savedInstanceState) {
32         super.onCreate(savedInstanceState);
33         setContentView(R.layout.activity_main);
34 
35         //得到控件
36         mCountdownTimeTextView= (TextView)findViewById(R.id.countdownTimeTextView);
37 
38         //创建了一个handler
39         CountdownTimeHandler handler = new CountdownTimeHandler(this);
40 
41         //新建了一个message
42         Message message = Message.obtain();
43         message.what = COUNTDOWN_TIME_CODE;
44         message.arg1 = MAX_COUNT;
45 
46         //第一次发送这个message
47         handler.sendMessageDelayed(message,DELAY_MILLIS);
48 
49     }
50 
51     public  static  class  CountdownTimeHandler extends Handler{
52           static  final  int  MIN_COUNT = 0;
53         final WeakReference<MainActivity> mWeakReference;
54 
55          CountdownTimeHandler(MainActivity activity){
56             mWeakReference = new WeakReference<> (activity );
57         }
58 
59         @Override
60         public void handleMessage(Message msg) {
61             super.handleMessage(msg);
62             MainActivity activity =mWeakReference.get();
63 
64             switch (msg.what){
65                 case COUNTDOWN_TIME_CODE:
66                     int value = msg.arg1;
67                     activity.mCountdownTimeTextView.setText(String.valueOf(value --));
68 
69                      //循环发的消息控制
70                     if (value >= MIN_COUNT) {
71                         Message message = Message.obtain();
72                         message.what = COUNTDOWN_TIME_CODE;
73                         message.arg1 = value;
74                         sendMessageDelayed(message, DELAY_MILLIS);
75                     }
76 
77                     break;
78             }
79         }
80     }
81 }
原文地址:https://www.cnblogs.com/juham/p/15141555.html