当前位置:网站首页>Thread handler handle IntentServvice handlerThread
Thread handler handle IntentServvice handlerThread
2022-08-05 05:38:00 【suiyue010211】
Thread
- 进程是系统分配资源的最小单位,线程是系统调度的最小单位.一个进程内的线程之间是可以共享资源的.每个进程至少有一个线程存在,即主线程.
androidThere are three ways to start child threads
继承Thread
class MyThead extends Thread{
@Override
public void run() {
super.run();
Log.i("接收", "收到: ");
}
}
MyThead myThead = new MyThead();
myThead.start();
实现Runnable接口
//Implement the interface to create child threads
class MyRunnable implements Runnable{
@Override
public void run() {
try {
Thread.sleep(5000);
Log.i("MyRunnable","child thread two");
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
MyRunnable myRunnable=new MyRunnable();
Thread thread=new Thread(myRunnable);
thread.start();
Thread和Runnable结合
//Use thread three in combination
new Thread(new Runnable() {
@Override
public void run() {
//耗时任务
try {
Thread.sleep(3000);
Log.i("结合线程","子线程三");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Child threads are used to proceed 耗时操作的
Handler
handler概念
- handler是一套 Android 消息传递机制,主要用于线程间通信.
- Describe it in the simplest terms: handlerIn fact, the main thread has a child thread,子线程运行并生成Message,Looper获取message并传递给Handler,HandlerGet the child threads one by oneMessage.
- Binder/Socket用于进程间通信,而Handler消息机制用于同进程的线程间通信
- 可以说只要有异步线程与主线程通信的地方就一定会有 Handler.
- 使用HandlerThe message passing mechanism is mainly for concurrent updates by multiple threadsUI的同时,保证线程安全
handler基本使用
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
String resule="999";
Message message=new Message();
message.what=1;
message.obj=resule;
handler.sendMessage(message);
} 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==1){
String obj = (String) msg.obj;
tv_1.setText(obj);
}
}
};
Send messages to in the child threadhandler,然后在handler接收消息,并获取what为1value and put itset给文本框
private ProgressBar pb_1;
int state;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
pb_1=findViewById(R.id.pb_1);
new Thread(new Runnable() {
@Override
public void run() {
while (state<100){
try {
Thread.sleep(1000);
state+=1;
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){
pb_1.setProgress(state);
}
}
};
这个是把stateThe value becomes a global variable,Then by increasingstateControls the growth of the progress bar,The above keeps increasing,一直循环到100;
IntentServvice
IntentService是Service的一个子类
创建IntentService的两种方式
第一种
创建Service继承IntentService接口
- 实现两个抽象方法
- 创建无参构造方法
- 在AndroidManifest.xmlopen entrance
<service
android:name=".MyIntentService"
android:exported="true" />
第二种
直接创建IntentService
- 删除所有内容
- 实现两个接口
- 创建无参构造函数
Service开启线程
Button btn_open_service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过id获取控件
btn_open_service = findViewById(R.id.btn_open_service);
//给按钮设置监听
btn_open_service.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,MyIntentService.class);
startService(intent);
}
});
}
public class MyService extends Service {
public MyService() {
}
@Override
public void onCreate() {
Log.i("Service has been created", "创建了: ");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Service has been created", "开启了: ");
new Thread(new Runnable() {
@Override
public void run() {
//当前时间加上20秒
long endtime = System.currentTimeMillis() + 20 * 1000;
while (System.currentTimeMillis()<endtime){
synchronized (this){
try {
wait(endtime-System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
stopSelf();
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("服务", "销毁了: ");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
IntentServvice开启线程
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
/**
* @param name
* @deprecated
*/
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i("IntentService","IntentService开启");
long endtime = System.currentTimeMillis() + 20 * 1000;
while (System.currentTimeMillis()<endtime){
synchronized (this){
try {
wait(endtime-System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onDestroy() {
Log.i("IntentService","IntentService销毁");
super.onDestroy();
}
}
Service和IntentServvice的区别
Service 不会自动开启线程,也不会自动关闭线程
IntentService 自动开启线程,自动关闭线程
HandlerThread
handlerThread还是一个线程,带了Looper的线程
public class MainActivity3 extends AppCompatActivity {
TextView tv_show2;
//线程
private HandlerThread handlerThread;
//The handle of the child thread
private Handler handler=new Handler();
//The handle of the main thread
private Handler mHandler=new Handler();
boolean isRun =true;
private String result="777";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
//根据id获取控件
tv_show2 = findViewById(R.id.tv_show2);
//创建handlerThreadand named him
handlerThread=new HandlerThread("check_massage");
handlerThread.start();
handler=new Handler(handlerThread.getLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
try {
Thread.sleep(2000);
result=result+1;
if (isRun)
handler.sendEmptyMessage(0x111);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
@Override
public void run() {
tv_show2.setText(result);
}
});
}
};
}
@Override
protected void onResume() {
super.onResume();
isRun=true;
handler.sendEmptyMessage(0x111);
}
@Override
protected void onPause() {
super.onPause();
isRun=false;
}
@Override
protected void onDestroy() {
super.onDestroy();
handlerThread.quit();
}
}
边栏推荐
猜你喜欢
轻松接入Azure AD+Oauth2 实现 SSO
【Pytorch学习笔记】9.分类器的分类结果如何评估——使用混淆矩阵、F1-score、ROC曲线、PR曲线等(以Softmax二分类为例)
Flutter 3.0升级内容,该如何与小程序结合
【数据库和SQL学习笔记】10.(T-SQL语言)函数、存储过程、触发器
【数据库和SQL学习笔记】3.数据操纵语言(DML)、SELECT查询初阶用法
AWS 常用服务
【数据库和SQL学习笔记】9.(T-SQL语言)定义变量、高级查询、流程控制(条件、循环等)
flink项目开发-配置jar依赖,连接器,类库
Flink EventTime和Watermarks案例分析
Matplotlib(二)—— 子图
随机推荐
门徒Disciples体系:致力于成为“DAO世界”中的集大成者。
MySql之索引
Lecture 3 Gradient Tutorial Gradient Descent and Stochastic Gradient Descent
flink项目开发-配置jar依赖,连接器,类库
【数据库和SQL学习笔记】4.SELECT查询2:排序(ORDER BY)、聚合函数、分组查询(GROUP BY)
Matplotlib(一)—— 基础
es6迭代协议
ES6 新特性:Class 的继承
Day1:用原生JS把你的设备变成一台架子鼓!
基于Flink CDC实现实时数据采集(二)-Source接口实现
Matplotlib(三)—— 实践
【论文精读】Rich Feature Hierarchies for Accurate Object Detection and Semantic Segmentation(R-CNN)
Flutter 3.0升级内容,该如何与小程序结合
day11-函数作业
My 的第一篇博客!!!
学习总结week2_3
学习总结week3_3迭代器_模块
ECCV2022 | RU&谷歌提出用CLIP进行zero-shot目标检测!
Convert the paper official seal in the form of a photo into an electronic official seal (no need to download ps)
轻松接入Azure AD+Oauth2 实现 SSO