当前位置:网站首页>Thread handler句柄 IntentServvice handlerThread
Thread handler句柄 IntentServvice handlerThread
2022-08-05 05:15:00 【suiyue010211】
Thread
- 进程是系统分配资源的最小单位,线程是系统调度的最小单位。一个进程内的线程之间是可以共享资源的。每个进程至少有一个线程存在,即主线程。
android三种方式开启子线程
继承Thread
class MyThead extends Thread{
@Override
public void run() {
super.run();
Log.i("接收", "收到: ");
}
}
MyThead myThead = new MyThead();
myThead.start();
实现Runnable接口
//实现接口创建子线程
class MyRunnable implements Runnable{
@Override
public void run() {
try {
Thread.sleep(5000);
Log.i("MyRunnable","子线程二");
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
MyRunnable myRunnable=new MyRunnable();
Thread thread=new Thread(myRunnable);
thread.start();
Thread和Runnable结合
//结合使用线程三
new Thread(new Runnable() {
@Override
public void run() {
//耗时任务
try {
Thread.sleep(3000);
Log.i("结合线程","子线程三");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
子线程是用来进行 耗时操作的
Handler
handler概念
- handler是一套 Android 消息传递机制,主要用于线程间通信。
- 用最简单的话描述: handler其实就是主线程在起了一个子线程,子线程运行并生成Message,Looper获取message并传递给Handler,Handler逐个获取子线程中的Message.
- Binder/Socket用于进程间通信,而Handler消息机制用于同进程的线程间通信
- 可以说只要有异步线程与主线程通信的地方就一定会有 Handler。
- 使用Handler消息传递机制主要是为了多个线程并发更新UI的同时,保证线程安全
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);
}
}
};
在子线程中发送消息到handler,然后在handler接收消息,并获取what为1的值并把他set给文本框
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);
}
}
};
这个是把state值变成全局变量,然后通过不断增加的state控制进度条的增长,上面不断增加,一直循环到100;
IntentServvice
IntentService是Service的一个子类
创建IntentService的两种方式
第一种
创建Service继承IntentService接口
- 实现两个抽象方法
- 创建无参构造方法
- 在AndroidManifest.xml开入口
<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("服务已创建", "创建了: ");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("服务已创建", "开启了: ");
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;
//子线程的句柄
private Handler handler=new Handler();
//主线程的句柄
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);
//创建handlerThread并给他起名字
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();
}
}
边栏推荐
- Using pip to install third-party libraries in Pycharm fails to install: "Non-zero exit code (2)" solution
- 【过一下6】机器视觉视频 【过一下2被挤掉了】
- [Go through 11] Random Forest and Feature Engineering
- 鼠标放上去变成销售效果
- 学习总结week3_3迭代器_模块
- Pycharm中使用pip安装第三方库安装失败:“Non-zero exit code (2)“的解决方法
- Flink HA安装配置实战
- 位运算符与逻辑运算符的区别
- 【MySQL】数据库多表链接的查询方式
- NodeJs接收上传文件并自定义保存路径
猜你喜欢
Lecture 5 Using pytorch to implement linear regression
[Go through 8] Fully Connected Neural Network Video Notes
[Let's pass 14] A day in the study room
软件设计 实验四 桥接模式实验
第二讲 Linear Model 线性模型
【零基础开发NFT智能合约】如何使用工具自动生成NFT智能合约带白名单可Mint无需写代码
pycharm中调用Matlab配置:No module named ‘matlab.engine‘; ‘matlab‘ is not a package
【NFT网站】教你制作开发NFT预售网站官网Mint作品
NodeJs接收上传文件并自定义保存路径
第5讲 使用pytorch实现线性回归
随机推荐
【读书】长期更新
[Go through 10] sklearn usage record
The fourth back propagation back propagation
Flink 状态与容错 ( state 和 Fault Tolerance)
Do you use tomatoes to supervise your peers?Add my study room, come on together
Flink Distributed Cache 分布式缓存
基于Flink CDC实现实时数据采集(一)-接口设计
拿出接口数组对象中的所有name值,取出同一个值
My 的第一篇博客!!!
学习总结week2_5
flink中文文档-目录v1.4
range函数作用
BFC详解(Block Formmating Context)
学习总结week3_1函数
[Over 17] Pytorch rewrites keras
Matplotlib(三)—— 实践
pycharm中调用Matlab配置:No module named ‘matlab.engine‘; ‘matlab‘ is not a package
软件设计 实验四 桥接模式实验
el-table鼠标移入表格改变显示背景色
Opencv中,imag=cv2.cvtColor(imag,cv2.COLOR_BGR2GRAY) 报错:error:!_src.empty() in function ‘cv::cvtColor‘