当前位置:网站首页>The practice of dual process guard and keeping alive in IM instant messaging development
The practice of dual process guard and keeping alive in IM instant messaging development
2022-06-28 01:37:00 【wecloud1314】
stay Android 4.4 And later systems , Whether the application can be resident in memory , It has always been a headache , Especially mobile terminal IM、 Message push applications , In order to ensure “ Full time online ” The concept of , It's been a lot of effort .
although APP Resident memory is more important for users ” nausea ”, But in places like IM And message push ,APP The resident memory is especially important , And many times users will also ask APP It can ensure long-term operation .
because Android There are too many and too many models , And customized by various manufacturers ROOM The difference of ,Android There is no one size fits all way to keep alive .

common Android Apply survival methods
1) Monitor broadcast mode :
By listening to some global static broadcasts , For example, start broadcasting 、 Unlock screen broadcast 、 Network status broadcast, etc , To start the background service of the application . at present , In high version Android The system has failed , Because of the higher version of Android The system stipulates that applications must run once after the system is powered on to listen to these system broadcasts , generally speaking , After the application is killed by the system , Basically unable to receive system broadcast .
2) Improve Service The priority of the :
Previous improvement Service There are many priority methods , such as onStartCommand return START_STICKY When the system memory is sufficient Service It can start automatically 、 Pop up notification 、 To configure service And so on , These methods can only alleviate service Be recycled immediately , However, as long as the user clicks one button to clean up or the system recycles, it is still invalid .
3) Global timer :
Another way is to set a global timer , Regularly detect and start the background service , But this method is no longer effective , Because as long as the application is killed by the system , The global timer finally became a decoration .
4) Double... In application service Pull up :
After testing , As long as the current app is killed , Any background service It doesn't work , Can not start by itself .
5) The two processes in the application pull up :
This method is the legendary use NDK In the underlying fork Make a sub process , To achieve mutual pull with the parent process . stay Android4.x It's still very effective , But the higher version Android The system recycling policy of the system has been changed to the form of process group , If the system wants to recycle an application , It must kill all processes belonging to the same process group , As a result, the dual processes cannot be pulled up .
analyse Android Of Service
Service The characteristics of are similar to Activity, The difference is that it has no interactive interface , And it can run in the background for a long time , Even if the application to which it belongs has exited ,Service You can still run in the background .Service Can't start on its own , Visitors can start it in two ways , namely startService( Binding ) and bindService ( Unbound ), The related introduction is as follows .
startService:
That is, unbound . Visitors use this method to start service after , Started service Will not be controlled by visitors , And no data communication with visitors , It will run indefinitely , Must call stopSelf() Methods or other components ( Including visitors ) call stopService() Method to stop . Its life cycle :onCreate->onStartCommand()->……>onDestory(), among ,onCreate Used to initialize work , Multiple calls startService Start the same service ,onCreate Methods are called only once ,onStartCommand Will be called many times ,onDestory It will only be called once when it is destroyed . Instant messaging development

bindService:
That is, binding form . Visitors use this method to start service after , Started service Controlled by visitors , Visitors will pass through a IBinder Interface object and bound service communicate , And through unbindService() Method is closed at any time service. One service It can be bound by multiple visitors at the same time , Only when multiple visitors actively unbind , The system will be destroyed service. Its life cycle :onCreate->onBind->....>onUnbind->onDestory, among ,onBind Used to return a communication object (IBinder) To visitors , Visitors can use this IBinder Object call service Related methods . When multiple visitors are bound to the same service when ,onCreate Will only be called once ,onBind、unOnbind The number of times that the method will be called in relation to the number of visitors ,onDestory It will only be called once when it is destroyed .
One thing to note is that : If one service By startService start-up , Then other components execute bindService Binding should service,service Of onCreate Will not be recalled again , It's a direct callback onBind Method ; When the component unBindService when ,service Of onUnbind Method called back , however service Will not be destroyed , Until you call stopSelf Method or other component calls stopService Method will be destroyed .
understand AIDL And remote Service call
Take the next section .bindService Start in binding mode service Divided into two : Local service And remote service.
Local service It refers to the binding initiated service Implementation in the application process to which it belongs , Other component visitors and local service The communication between the IBinder Interface object implementation ; long-range service It refers to the binding initiated service Implementation in other application processes , That's another one APP in , Their communication is through IBinder Interface , The proxy object must pass through AIDL To construct .
AIDL(Android Interface DefinitionLanguage, Interface description language ) Use rules that restrict communication between two processes , Can achieve Android Two different applications on the terminal ( process ) Communication between (IPC).
AIDL The implementation steps are very simple , The explanation is as follows :
1) stay A Application creation IPerson.aidl Interface file ( Be careful AIDL The rules of language writing , It's not detailed here );
2) Will create the IPerson.aidl Copy interface files to B Application .
packagecom.person.aidl
interfaceIPerson{
String getName();
intgetAge();
then : We just need to save .aidl file , The compiler will automatically generate the required IPerson.java file , Save in gen Under the table of contents , This file contains an inner class IPerson.Stub, It actually inherits from Binder object , That is, to act as the necessary for communication IBinder Proxy object .
There are a few caveats here , It will affect whether the two processes can communicate successfully :
1) Interface name and aidl Same file name ;
2) application A、 application B Medium .aidl The files must be the same , And the package names to which they belong must be the same .
Let's take a look at how the single process daemon can keep alive
Let's first analyze the binding mode startup Service technological process .
With a Android application ( Hereinafter referred to as application X) The guardian of Service Start the survival assistant A The guardian of Service For example :
1) When an application X Medium Service adopt bindService Bind the survival assistant A Of Service when , Keep alive assistant A Callbacks onBind Method returns a IPerson.Stub Proxy object to the application X;
2) When an application XService Medium onServiceConnected When called back , Explain the application X Bind the survival assistant A Of Service success ;
3) When unbinding , application X Medium onServiceDisconnected And a survival assistant A Medium onUnbind Called .
With the foundation in front , Next, we will analyze how to create daemons in different application processes service, Wake up each other by detecting their binding :
1) When an application X Bind the survival assistant A when ( Light green font ), If the survival assistant A Killed by the system , application X Of onServiceDisConnected Called back , We can execute... In this method bindService Method tries to bind the wake-up helper again A;
2) Be a survival assistant A Binding application X when ( Orange font ), If the application X Killed by the system , Keep alive assistant A Of onServiceDisconnected Called back , We can execute... In this method bindService Method attempts to bind the wakeup application again X.
thus , The purpose of keeping the application alive is achieved through this double binding and guarding .
The new dual process daemon keeps alive
To some extent , The single process daemon can almost meet the requirements of keeping applications alive for a long time , Although it feels a little strange , But it is not very difficult to implement , Obvious effects .
however , With further testing , I killed the app twice in a row X, application X It won't start , This is because when applying X“ Volume ” more , You need to load a large number of static variables or Application Variables in classes, etc , Cause slow startup , When I first killed the app X when , Keep alive assistant A Is to execute binding to start the application X The life insurance service , But I continue to kill the application for the second time X when , Keep alive assistant A It may not be related to the application X binding , Eventually lead to the survival assistant A Unable to check app X The binding state of the .
Dual process daemons : For problems with single process daemons , When an application X“ Volume ” large , We can use dual process daemon , That is, to realize two survival assistants , They are Bi directionally bound to each other to apply X Guard . We use “ Ring ” To pull each other , Whoever is killed , As long as the system kills any remaining processes , Finally, the living process can pull up other killed processes . Of course , Here's another tip , To prevent two keep alive assistant processes from being killed by the system at the same time , I have adopted a high and low priority approach to solve .
边栏推荐
- 吸顶方案1
- 【DNS 解析】将Name.com的域名接入DNSPod解析
- lefse分析本地实现方法带全部安装文件和所有细节,保证成功。
- Latest MySQL advanced SQL statement Encyclopedia
- 独立站卖家都在用的五大电子邮件营销技巧,你知道吗?
- Ten thousand words long article understanding business intelligence (BI) | recommended collection
- What are the requirements for customizing the slip ring for UAV
- Ai+ clinical trial patient recruitment | massive bio completed round a financing of $9million
- What problems should be evaluated before implementing MES management system
- Meituan dynamic thread pool practice idea has been open source
猜你喜欢

MapReduce elementary programming practice
![The number of nodes of a complete binary tree [non-O (n) solution > Abstract dichotomy]](/img/56/768f8be9f70bf751f176e40cbb1df2.png)
The number of nodes of a complete binary tree [non-O (n) solution > Abstract dichotomy]

联想拯救者R720如何组建双通道内存

Overview and construction of redis master-slave replication, sentinel mode and cluster

如何在您的Shopify商店中添加实时聊天功能?

面试官问:JS的继承

Taro---day1---搭建项目

什么是数字化?什么是数字化转型?为什么企业选择数字化转型?

评价——灰色关联分析

The research group of Xuyong and duanwenhui of Tsinghua University has developed an efficient and accurate first principles electronic structure deep learning method and program
随机推荐
同花顺上能炒股开户吗?安全吗?
Adobe Premiere基础-声音调整(音量矫正,降噪,电话音,音高换挡器,参数均衡器)(十八)
What is a through-hole conductive slip ring?
如何高效读书学习
Class文件结构和字节码指令集
Modular development
. Mp4 video test address
Deep parsing of kubernetes controller runtime
什么是数字化?什么是数字化转型?为什么企业选择数字化转型?
什么是过孔式导电滑环?
Cloud native O & M article plan
Supervised, unsupervised and semi supervised learning
What is the e-commerce conversion rate so abstract?
现在炒股网上开户安全吗?新手刚上路,求答案
Arrays.asList()坑
药物发现综述-03-分子设计与优化
如何理解 Transformer 中的 Query、Key 与 Value
Adobe Premiere基础-常用的视频特效(边角定位,马赛克,模糊,锐化,手写工具,效果控件层级顺序)(十六)
药物发现综述-01-药物发现概述
lodash实现防抖和节流功能及原生实现