当前位置:网站首页>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
边栏推荐
- SSH远程管理
- The first positive number missing in question 41 of C language. Two methods, preprocessing, fast sorting and in situ hashing
- 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
- Use playbook in ansible
- Hack The Box -SQL Injection Fundamentals Module详细讲解中文教程
- It's enough for newcomers to learn how to do functional tests
- 高分子物理试题库
- DOM操作--操作节点
- 517. Super washing machine
- Basic methods of realizing licensing function in C language
猜你喜欢
随机推荐
Trend of the times - the rise of cloud native databases
Migrate the server and reconfigure the database (the database has no monitoring, and the monitoring starts with tns-12545, tns-12560, tns-00515 errors)
nn.Moudle模块-创建神经网络结构需要注意的细节
LeetCode链表问题——203.移除链表元素(一题一文学会链表)
The first positive number missing in question 41 of C language. Two methods, preprocessing, fast sorting and in situ hashing
An online accident, I suddenly realized the essence of asynchrony
DOM event flow event bubble event capture event delegate
嵌入式开发小记,实用小知识分享
C语言-指针进阶
ALV program collection
Meta analysis [whole process, uncertainty analysis] method based on R language and meta machine learning
no networks found in /etc/cni/net.d
Real scientific weight loss
C语言实现发牌功能基本方法
C语言详解系列——函数的认识(4)函数的声明与定义,简单练习题
CMD operation command
普林斯顿微积分读本02第一章--函数的复合、奇偶函数、函数图像
It's enough for newcomers to learn how to do functional tests
List converted to tree real use of the project
ALV程序收集









