当前位置:网站首页>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 .
边栏推荐
- Redis configuration and optimization of NoSQL
- .mp4视频测试地址
- Is there any risk in opening an account for flush stock? Is it safe for flush to open an account
- Xctf attack and defense world misc wage earner advanced zone
- Web3 technology initial experience and related learning materials
- 电商转化率这么抽象,到底是个啥?
- Interviewer asked: Inheritance of JS
- Modular development
- 数据库查询优化:主从读写分离及常见问题
- What problems should be evaluated before implementing MES management system
猜你喜欢
随机推荐
FB、WhatsApp群发消息在2022年到底有多热门?
What are cookies and the security risks of v-htm
Adobe Premiere基础-声音调整(音量矫正,降噪,电话音,音高换挡器,参数均衡器)(十八)
Download, configuration and installation of MySQL
I/O限制进程与CPU限制进程
Huawei partners and Developers Conference 2022 | Kirin software cooperates with Huawei to jointly build the computing industry and create a digital intelligence future
评价——灰色关联分析
How to read a paper
MySQL 18: execution of write statements
Proe/creo product structure design - continuous research
手机股票开户安全吗,买股票在哪开户?
Adobe Premiere基础-编辑素材文件常规操作(脱机文件,替换素材,素材标签和编组,素材启用,便捷调节不透明度,项目打包)(十七)
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
模块化开发
N methods of data De duplication using SQL
What is digitalization? What is digital transformation? Why do enterprises choose digital transformation?
Redis configuration and optimization of NoSQL
Deep parsing of kubernetes controller runtime
Taro--- day2--- compile and run
Is there any risk in opening an account for flush stock? Is it safe for flush to open an account







