服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android中子线程和UI线程通信详解

Android中子线程和UI线程通信详解

2021-03-24 15:59Android开发网 Android

这篇文章主要介绍了Android中子线程和UI线程通信详解,本文讲解了一些概念、使用、及代码实例,需要的朋友可以参考下

Android中子线程和UI线程之间通信的详细解释

1.在多线程编程这块,我们经常要使用Handler,Thread和Runnable这三个类,那么他们之间的关系你是否弄清楚了呢?下面详解一下。
2.首先在开发Android应用时必须遵守单线程模型的原则:
Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行。
3.Handler:
(1).概念:
Handler是沟通Activity 与Thread/runnable的桥梁。而Handler是运行在主UI线程中的,它与子线程可以通过Message对象来传递数据。
(2).使用:
A:Handler是运行在UI线程中,主要接收子线程发送的数据信息, 并用此数据配合主线程更新UI,用来跟UI主线程交互用。比如可以用handler发送一个message,然后在handler的线程中来接收、处理该消息。
B:消息的处理者。通过Handler对象我们可以封装Message对象,然后通过sendMessage(msg)把Message对象添加到MessageQueue中;当MessageQueue循环到该Message时,就会调用该Message对象对应的handler对象的handleMessage()方法对其进行处理。
C:Handler可以分发Runnable对象,也可以分发Message对象。

4.Message:
 消息对象,顾名思义就是记录消息信息的类。也就是说是信息的载体,存放信息内容。这个类有几个比较重要的字段:

  (1).arg1和arg2:我们可以使用两个字段用来存放我们需要传递的整型值,在Service中,我们可以用来存放Service的ID。
  (2).obj:该字段是Object类型,我们可以让该字段传递某个对象到消息的接受者中。
  (3).what:这个字段可以说是消息的标志,判断是接收了哪个消息。在消息处理中,我们可以根据这个字段的不同的值进行不同的处理,类似于我们在处理Button事件时,通过switch(v.getId())判断是点击了哪个按钮。
Android推荐通过Message.obtain()或者Handler.obtainMessage()获取Message对象。这并不一定是直接创建一个新的实例,而是先从消息池中看有没有可用的Message实例,存在则直接取出并返回这个实例。反之如果消息池中没有可用的Message实例,则根据给定的参数new一个新Message对象。通过分析源码可得知,Android系统默认情况下在消息池中实例化10个Message对象。
5.源码展示:
(1).activity_main.xml布局文件:

?
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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/container"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
 
  <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="自定义Thread继承Thread" />
 
 
  <Button
    android:id="@+id/btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="自定义Runnable实现Runnable" />
 
 
  <Button
    android:id="@+id/btn3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="定时更新UI界面,Handler分发Runnable对象" />
 
 
  <Button
    android:id="@+id/btn4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="定时更新UI界面,Handler分发Message对象" />
 
  <TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0" />
 
</LinearLayout>

(2).MainActivity.java

?
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package com.chengdong.su.threaddemo;
 
import com.chengdong.su.threaddemo.util.MyRunnable;
import com.chengdong.su.threaddemo.util.MyThread;
 
import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
 
public class MainActivity extends Activity implements OnClickListener {
  /** TAG */
  private final String TAG = getClass().getSimpleName();
  /** the object of the button */
  private Button mButton;
  /** the object of the button */
  private Button mButton2;
  /** the object of the button */
  private Button mButton3;
  /** the object of the button */
  private Button mButton4;
  /** the object of the TextView */
  private TextView mTextView;
  /** 计数 */
  private int mCount = 0;
  /** 标志 */
  private int MESSAGE_FLAG = 1;
 
  /**
   * Handler分发Runnable对象的方式
   */
  private Handler mHandler = new Handler();
 
  Runnable runnable = new Runnable() {
 
    @Override
    public void run() {
      mCount++;
      mHandler.postDelayed(runnable, 1000);
      mTextView.setText(mCount + "");
 
    }
  };
  /***
   * Handler分发Message对象的方式
   */
 
  Handler mHandler2 = new Handler() {
    public void handleMessage(android.os.Message msg) {
      if (msg.what == 1) {
 
        mTextView.setText("Handler分发Message对象的方式");
      }
    }
  };
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
 
  }
 
  /**
   * 初始化组件对象
   */
  private void initView() {
    mButton = (Button) findViewById(R.id.btn);
    mButton2 = (Button) findViewById(R.id.btn2);
    mButton3 = (Button) findViewById(R.id.btn3);
    mButton4 = (Button) findViewById(R.id.btn4);
 
    mButton.setOnClickListener(this);
    mButton2.setOnClickListener(this);
    mButton3.setOnClickListener(this);
    mButton4.setOnClickListener(this);
 
    mTextView = (TextView) findViewById(R.id.tv);
 
  }
 
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn: {
      // 方法一:继承的方式:自定义Thread继承Thread,开启一个新的线程
      new MyThread().start();
      break;
    }
    case R.id.btn2: {
      // 方法二:实现的方式:implement Runnable
      new Thread(new MyRunnable()).start();
      break;
    }
    // 方法三:handler分发Runnable对象:定时更新UI界面 提交计划任务马上执行
    case R.id.btn3: {
 
      // Handler分发Runnable对象
      mHandler.post(runnable);
      break;
    }
    // 方法四:Handler分发Message对象 ,定时更新UI界面 提交计划任务马上执行
    case R.id.btn4: {
 
      // 不推荐这种方式
      // Message msg = new Message();
      // 推荐使用这种获取对象的方式:从消息池中获得可用的Message对象
      Message msg = Message.obtain();
      msg.what = MESSAGE_FLAG;
      mHandler2.sendMessage(msg);
      break;
    }
 
    default:
      break;
    }
 
  }
}

(3).MyRunnable.java

?
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
package com.chengdong.su.threaddemo.util;
 
import android.util.Log;
 
/***
 * 自定义一个MyRunnable线程
 *
 * @author scd
 *
 */
public class MyRunnable implements Runnable {
 
  public MyRunnable() {
    super();
  }
 
  /** TAG */
  private final String TAG = getClass().getSimpleName();
 
  @Override
  public void run() {
    for (int i = 0; i < 20; i++) {
      Log.e(TAG, Thread.currentThread().getName() + ",实现的方法" + i);
 
    }
 
  }
 
}

(4)MyThread.java

?
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
package com.chengdong.su.threaddemo.util;
 
import android.util.Log;
 
/***
 * 自定义一个线程
 *
 * @author scd
 *
 */
public class MyThread extends Thread {
 
  public MyThread() {
    super();
  }
 
  /** TAG */
  private final String TAG = getClass().getSimpleName();
 
  @Override
  public void run() {
    super.run();
    for (int i = 0; i < 10; i++) {
      Log.e(TAG, Thread.currentThread().getName() + ",继承Thread类:" + i);
 
    }
  }
 
}

 

延伸 · 阅读

精彩推荐