当前位置:网站首页>Three implementation methods of thread and the usage of handler
Three implementation methods of thread and the usage of handler
2022-07-26 05:24:00 【shuo277】
The first way :
class MyThread extends Thread{
public void run(){
// Write time-consuming operation code
// Only the original thread that created a view hierarchy can touch its views.
// If the child thread has performed a time-consuming operation , Then you can't modify the properties of the view ; View properties can only be in UI Thread to modify
}
}
MyThread myThead = new MyThread();
myThread.start();The second way :
class MyRunnable implements Runnable {
@Override
public void run() {
try {
Thread.sleep(3000);
String result = "runnable 345345";
Log.i("runnable", result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();The third way :( common 、 recommend )
new Thread(new Runnable() {
@Override
public void run() {
// Time consuming tasks
try {
Thread.sleep(3000);
String result = " Anonymous threads ";
Log.i(" Anonymous threads ",result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();3、Handler
/**
* Received the user's nickname from the server , And set the nickname to textview Corresponding text Attribute
*
* The function of connecting to the server , It's a time-consuming task , So it must be placed in the sub thread
*
* There is no way to modify the page in the sub thread , With the help of Handler Pass messages to the main thread
*
* After the main thread receives the message , Start the modification UI
*/
public class MainActivity2 extends AppCompatActivity {
// Declaring container
private TextView tv1;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);// according to ID Get page control
tv1 = findViewById(R.id.tv1);// Simulate the process of connecting to the server
new Thread(new Runnable() {
@Override
public void run() {
try {
// The original intention is to express The time-consuming operation of connecting to the server
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// If the nickname obtained from the server is : Deep fried
String result = " Deep fried ";
// Give a nickname to textview Set up , Update... In child threads UI, It's not allowed , You have to use handler Pass the message back
Message message = new Message();
message.what = 1;
message.obj = result;
handler.sendMessage(message);}
}).start();
}private Handler handler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);if (msg.what == 1) {
String result = (String) msg.obj;
tv1.setText(result);
}}
};
}
4 Progress bar
public class MainActivity3 extends AppCompatActivity {
private ProgressBar progressBar;
int status = 0;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);progressBar = findViewById(R.id.progressBar);
new Thread(new Runnable() {
@Override
public void run() {
// Cycle pair status Make it worth modifying
while (status < 100) {
try {
Thread.sleep(100);
status++;
handler.sendEmptyMessage(0x111);
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
}).start();
}private Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 0x111) {
progressBar.setProgress(status);
}
}
};
}
5.Service solve ANR
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("serivce"," Service is turned on ");new Thread(new Runnable() {
@Override
public void run() {
long endtime = System.currentTimeMillis() + 20 * 1000; // Get the current system plus 20 second
while(System.currentTimeMillis() < endtime) {
synchronized (this){
try {
wait(endtime - System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
stopSelf();
}
}).start();return super.onStartCommand(intent, flags, startId);
}
Conclusion :
Service The thread will not start automatically , It will not automatically stop the thread
6 IntentService
How to create a IntentService
new Class-> MyIntentService -> Inherit IntentService-> Realization onHandleIntent and Construction method
stay AndroidManifest.xml Register in , An error is reported during registration , The reason for the error is that there is no parameter free construction method , terms of settlement : Create parameterless construction methods

Activity The long-running Sub thread , handler
Service IntentService Automatically start the thread , And after the execution , Close thread
边栏推荐
- Yuancosmos provides a digital social platform for fashion design display
- ALV报表流程图解
- C language function
- Recommend 12 academic websites for free literature search, and suggest to like and collect!
- ALV程序收集
- MongonDB API使用
- DOM事件流 事件冒泡-事件捕获-事件委托
- no networks found in /etc/cni/net.d
- 如何从内存解析的角度理解“数组名实质是一个地址”?
- 元宇宙为服装设计展示提供数字化社交平台
猜你喜欢

How to reproduce the official course of yolov5 gracefully (II) -- Mark and train your own data set

没背景、没学历?专科测试员进入互联网大厂是不是真的没希望?

Security permission management details

普林斯顿微积分读本02第一章--函数的复合、奇偶函数、函数图像

Shell process control (emphasis), if judgment, case statement, let usage, for ((initial value; loop control condition; variable change)) and for variable in value 1 value 2 value 3..., while loop

Shell的read 读取控制台输入、read的使用

C语言力扣第41题之缺失的第一个正数。两种方法,预处理快排与原地哈希

Recommended reading: how can testers get familiar with new businesses quickly?

高频电子线路复习考试题及答案

no networks found in /etc/cni/net.d
随机推荐
Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
Shell的read 读取控制台输入、read的使用
Embedded development notes, practical knowledge sharing
10. Regular expression matching
jupyter notebook快捷键
MySQL basic learning
If MySQL calculates the current month change / current month increase / year-on-year change / year-on-year increase?
Yolov5 implementation process - Directory
no networks found in /etc/cni/net.d
ABAP语法学习(ALV)
测试必备工具之Fiddler,你真的了解吗?
动态内存管理及柔性数组
高分子物理知识点
Earth system model (cesm) practical technology
Okaleido上线聚变Mining模式,OKA通证当下产出的唯一方式
LeetCode链表问题——203.移除链表元素(一题一文学会链表)
LNMP架构
OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation
35. 搜索插入位置
Webassembly 01 basic information