当前位置:网站首页>Handler asynchronous message passing mechanism (I) common basic usage of handler
Handler asynchronous message passing mechanism (I) common basic usage of handler
2022-04-21 09:03:00 【Rumina】
Statement : There is no charge for this tutorial , Welcome to reprint , Respect the work of the author , Not for commercial use , Infringement must be investigated !!!
Catalog
1、Handler Object sends a message to the newly started child thread
2、 Create in main thread Handler、 And get the processing message
2、Handler Common problems that can be solved ?
Series articles
Handler Asynchronous messaging mechanism ( One )Handler Common basic usage
Handler Asynchronous messaging mechanism ( Two ) Create... In a child thread Handler
One 、 brief introduction
Android The message passing mechanism of is mainly to solve Android Multithreading of applications , and Android The platform does not allow Activity The newly started child thread accesses this Activity The interface components inside , This will make the newly started thread unable to dynamically change the property value of the interface component .
Such as :Android In actual development , Especially when it comes to game development, new threads are often required , Periodically access and change the attribute values of interface components . So how to solve it ? We can use Handler、AsyncTask Relevant mechanisms to solve .
This article is mainly about Handler, of AsyncTask For reference :Android Special topic AsyncTask( One ) Introduction to basic concepts
1、Handler How to implement ?
(1) Create in main thread Handler, Get through callback 、 Process the message
(2) Send a message in a newly started thread
2、 Send and process messages
In order to make the main thread better handle the messages sent by the newly started thread , Obviously, only through The way of callback To achieve .
Developers just need to rewrite Handler Class to process messages , When a newly started child thread sends a message ,Handler Class is automatically called back .
Handler Class contains the following methods to send 、 Process the message :

![]()
Two 、 Practical cases
Here I'll take the previous project “app Download updates and install them automatically ” The code has been changed , Because it's mainly a demonstration Handler Usage of , So the other steps are presented in the form of simulation or output !
1、Handler Object sends a message to the newly started child thread
Simulation download app, And send a message to the newly started child thread
public class DownLoadAppFile {
public void download(String urlPath, Handler handler, ProgressBar pb) {
try {
// download apk Code for , Here, thread sleep is used to simulate
Thread.currentThread().sleep(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = Message.obtain();
msg.what =1;// success
//msg.what =2;// Failure
handler.sendMessage(msg);//( Sub thread ) Send a message
}
}
2、 Create in main thread Handler、 And get the processing message
public class MainActivity extends AppCompatActivity {
private TextView show_text;
private String strMsg;
// Get... In the main thread 、 Process the message
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:// Download successful
strMsg = strMsg +"\n"+ "2、apk Download successful ... Start automatic installation of downloaded apk!";
show_text.setText(strMsg);
Toast.makeText(MainActivity.this,"apk Download successful !",Toast.LENGTH_SHORT).show();
break;
case 2:// Download failed
strMsg = strMsg +"\n"+ "apk Download failed !";
show_text.setText(strMsg);
Toast.makeText(MainActivity.this,"apk Download failed !",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show_text = (TextView) findViewById(R.id.show_text);
downloadApkFile();
}
/**
* download apk file
* notes :Android 6.0 The above need to apply for read-write permission
*/
private void downloadApkFile() {
strMsg = "1、 Start the download apk...";
show_text.setText(strMsg);
Toast.makeText(MainActivity.this," Start the download apk...",Toast.LENGTH_SHORT).show();
new Thread() {// In the newly started child thread , Call Download app Code for , And send messages 、 Feedback results
public void run() {
DownLoadAppFile downLoadFile = new DownLoadAppFile();
downLoadFile.download(null, handler, null);
};
}.start();
}
}
3、demo Demonstration effect
demo Address :https://download.csdn.net/download/yudbl/10894028
The effect is as follows :

3、 ... and 、 To sum up
1、Handler Basic usage
(1) Create in main thread Handler, Get through callback 、 Process the message
(2) Send a message in a newly started thread
2、Handler Common problems that can be solved ?
problem :
The newly started thread cannot dynamically change the attribute value of the interface component
reason :
Android The message passing mechanism of is mainly to solve Android Multithreading of applications ,
and Android The platform does not allow Activity The newly started child thread accesses this Activity The interface components inside .
Examples of common usage scenarios :
(1)app Upgrade download installation , Update the progress bar in real time
(2) Game development often requires newly started threads , Periodically access and change the attribute values of interface components
版权声明
本文为[Rumina]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210854254924.html
边栏推荐
- 目标检测入门常见问题(深度学习 / 图像分类)
- 内网渗透-代理穿透-提权-注入-msf-中间件-域渗透-日志清除-学习资源
- Remove linked list elements < difficulty coefficient >
- Notice on organizing the application of the first set of technical equipment and key core parts project in Shandong Province in 2022
- 电脑常用快捷键+常用Dos命令
- Meizu, once expected to challenge apple, now lives by providing accessories for Apple users
- 移除链表元素 <难度系数>
- Garbage collection mechanism
- BUUCTF[HCTF 2018]WarmUp
- 【CVPR 2020】PointASNL :Robust Point Clouds Processing using Nonlocal Neural Networks
猜你喜欢

2022 mobile crane driver examination exercises simulated examination platform operation

中国移动的用户ARPU重新进入上升通道,员工薪酬也稳步上涨
![BUUCTF[ACTF2020 新生赛]Include](/img/20/3c0d0286c869385ee0c9a119e337e2.png)
BUUCTF[ACTF2020 新生赛]Include
![Grid division [DFS]](/img/39/1929a57b7305a49292ef3972afa8a3.png)
Grid division [DFS]
![Buuctf [actf2020 freshman competition] include](/img/20/3c0d0286c869385ee0c9a119e337e2.png)
Buuctf [actf2020 freshman competition] include

原生与H5混合式开发详解

CC10000.CloudJenkins—————————————

内网渗透-代理穿透-提权-注入-msf-中间件-域渗透-日志清除-学习资源
![Buuctf [geek challenge 2019] havefun](/img/5a/9b1942c0d24f079be804c7b3304be1.png)
Buuctf [geek challenge 2019] havefun

L2-026 小字辈 (25 分)
随机推荐
Actual combat analysis of PC wechat robot personal number interface API wechat agrees with friend call
Major programming languages and applications in 2022
Open3d读写pcd点云文件
Convolution operation and cross correlation operation
Based on ASP Net online flower shopping management
Theme model of image
51 single chip microcomputer learning_ 1.3 LED water lamp
Common computer shortcut keys + common DOS commands
某系统拥有N个进程,总共7个资源,每个进程需要3个资源,问N数量最多为多少不会死锁?(附解析)
ShardingSphere简介
我的博客导航目录(持续整理更新中。。。)
最新系统漏洞--OMERO.web跨站脚本漏洞
CC00043.CloudJenkins—————————————
CC00019.CloudJenkins—————————————
Uniapp hot update and full package update
Buuctf [geek challenge 2019] easysql
Add log4j log function
加入log4j日志功能
[CTF. Show. Reverse] reverse AK race easydse
Penetration practice - no echo rce thinkphp5 getshell