当前位置:网站首页>Do you use thread or service?
Do you use thread or service?
2022-06-22 19:26:00 【Liuyichu】
In the last article we said Threa and Service It doesn't matter . It basically explains their differences , But the depth is not enough , In this article, we continue to discuss thread and Service!
Let's talk about it first. Thread and Service Some of the differences :
Thread:Thread ( Threads ) Is the smallest unit of program execution , It can be used Thread To perform some asynchronous operations .
Thread The operation of is independent . When one Activity By finish after , If there is no active stop Thread perhaps Thread Inside run If the method is not finished ,Thread And it's going to be carried out all the time . So there's a problem here : When Activity By finish after , No longer hold the Thread References to , And you can no longer control the Thread. On the other hand , There is no way in different Activity Center to same Thread Control .
Service:Service yes android A mechanism of , When it's running, if it's Local Service, So the corresponding Service Is running on the main thread of the main process . If it is Remote Service, So the corresponding Service It runs on the main thread of an independent process .( We talked about that in the last post RemoteService Of )
for example : If One Thread You need to connect to the server at regular intervals to verify the data , The Thread It needs to be running all the time in the background . At this time, if you create this Thread Of Activity It's over and it's time Thread Didn't stop , Then there will be no way to control the Thread, Unless you kill the process of the program . At this point, if you create and start a Service , stay Service It creates 、 Run and control the Thread, This solves the problem ( Because of anything Activity Can be bound to the same Service, And the system will only create a corresponding Service Example ).
So we can Service Think of it as a messaging service , Can be anywhere there is Context Local call to startService or bindService To control it , It can also be in Service Registered in the BroadcastReceiver, By sending broadcast To achieve the purpose of control , These are all Thread Impossible .
Look again. Service Several characteristics of :
(1) By default ,Service Is running in the main thread , If you need to perform complex and time-consuming operations , Must be in Service Create another Thread To perform the task , To avoid ANR.
(2) Service Priority of is higher than that of Activity. Of course , Also higher than in Activity Created in Thread. therefore , The system may give priority to killing the background when the memory is insufficient Activity perhaps Thread, And will not easily kill Service Components , Even if forced to kill Service, It will also restart the killed when resources are available Service.
Actually ,Service and Thread It is not a level thing at all ,Service Is one of the four components of the system . and Thread It is just a tool class used to perform background tasks , It can be Activity Is created in , It can also be in Service Is created in .
therefore , The root of this problem should be , We should not discuss the use of Service still Thread, Instead, we should discuss Where to create Thread?
Typical applications , It can be created in three places , Different locations , Its life cycle is different , therefore , We should be According to the Thread The target life cycle is determined in Service Created in Thread Still Activity Create it in .
(1) stay Activity Is created in
Generally in onCreate Created on , stay onDestroy() Medium destruction , otherwise ,Activity After destruction ,Thread Will still be running in the background .
In this case ,Thread The life cycle of is the whole Activity Life cycle of . therefore , stay Activity Created in the Thread Only suitable for completing some dependencies Activity Tasks related to itself , For example, update regularly Activity Control status, etc .
Core features : The Thread That's why Activity Service , Complete this particular Activity The task assigned , Take the initiative to inform the Activity Some news and events ,Activity After destruction , The Thread There's no point in living .
(2) stay Application Is created in
General customization Application class , heavy load onCreate Method , And create Thread, Of course , Will also be in onTerminate() Method of destruction Thread, otherwise , If Thread If you don't quit , Even if the whole Application Out of the ,Thread Still running in the background .
In this case ,Thread The life cycle of is the whole Application Life cycle of . therefore , stay Application Created in the Thread, It can perform some tasks at the whole application level , For example, regularly check the network connection status and so on .
Core features : The Thread The ultimate goal is for this APP Each of them Activity Service , Including completing a Activity The task assigned , Take the initiative to inform someone Activity Some news and events, etc ,APP After exiting, you should Thread There's no point in living .
In both cases ,Thread The life cycle of should not exceed the entire application life cycle , That is to say , Whole APP After you quit ,Thread Should quit completely , So there won't be memory leaks or zombie threads . that , If you want the whole APP Can still run this after exiting Thread, Then we should put Thread Put it in Service To create and launch .
(3) stay Service Is created in
This is to guarantee the longest life cycle Thread The only way , As long as the whole Service Do not exit ,Thread It can be executed in the background all the time , Generally in Service Of onCreate() Created in , stay onDestroy() Medium destruction .
therefore , stay Service Created in the Thread, Suitable for long-term execution some independent of APP Background tasks for , The common one is : stay Service Keep a long connection with the server side .
Core features : The Thread It can be for APP Provide some “ service ” perhaps “ State query ”, But it's time to Thread There is no need to take the initiative to inform APP Any incident , You don't even need to know APP Who is it? .
All in all , We're not thinking about using Thread Or should I use it Service, It should be for Thread Choose the right life cycle , This is my right to Service and Thread Thinking and understanding .
边栏推荐
- ssh免密码登录
- 2年狂赚178亿元,中国游戏正在“收割”老外
- Is flush easy to open an account? Is it safe to open a mobile account?
- Iplook 5gc successfully connected with CICA international CHF (billing function)
- Shell script explanation (II) -- conditional test, if statement and case branch statement
- 一些技术想法:
- Method of activity jump to fragment (intent)
- 如何更改Apple Watch上的表盘
- Modèle de langage de pré - formation, Bert, roformer Sim aussi connu sous le nom de simbertv2
- 有效的括号
猜你喜欢

Service实战:使用Service完成一个下载任务
Set of redis data structure

2022 Chongqing preschool education industry exhibition 𞓜 hi tech Toy Puzzle decompression Toy Expo

下拉刷新及上拉加载更多的ListView

泡泡玛特:空洞的灵魂需要故事

shell脚本详解(四)——循环语句之while循环和until循环(附加例题及解析)

缓存3种方式及原理

IPLOOK 5GC与亚信国际CHF(计费功能)对接成功

Activity跳转到Fragment的方法(Intent)

集群、分布式、微服务概念和区别
随机推荐
贪心之区间问题(3)
Which securities company is better to open an account when making an appointment to play new bonds? It is safer to open an account
Dynamically changing the style of label elements in a loop
What happened to this page when sqlserver was saving
Method of activity jump to fragment (intent)
Sre is bound to move towards the era of chaotic engineering -- Huawei cloud chaotic engineering practice
面试MySQL
vs code突然无法进行代码跳转
Exness sorted out three problems to be solved in Musk's acquisition of Twitter
STM32控制矩阵按键,HAL库,cubeMX配置
集群、分布式、微服务概念和区别
Flush difficult to open an account? Is it safe to open an account online?
有效的括号
Complete the sqlsession interface and implementation classes
DBMS in Oracle_ output. put_ Example of line usage
Several important viewpoints on operation and maintenance, monitoring and aiops
Implementing Domain Driven Design - using ABP framework - solution overview
JVM quick start
消息中间件(一)MQ详解及四大MQ比较
贪心之分配问题(1)