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