当前位置:网站首页>Im instant messaging development application keeping alive process anti kill
Im instant messaging development application keeping alive process anti kill
2022-06-24 23:56: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 .
therefore , With a skeptical eye , Retrieve the original code for testing , Incidentally, the mainstream sports in the market are analyzed APP Method of keeping alive ( WeChat 、 hand Q Forget it , The children of the rich , Not representative ), At the same time, it is also applicable to the system and the memory APP The management rules of .

Andriod Apply the core idea of keeping alive to sum up
about Android6.0 And above APP Keep alive , I think it is mainly through these two aspects , namely :
Reduce omm_adj value , Try to ensure that the process is not killed by the system ( What this article will discuss );
After the process is killed , Reactivate the process in other ways ( We will discuss in the next article ).
But it needs to be understood that , Facing the deep customization of various mobile phone manufacturers and Google's increasingly strict resource management mechanism , The combination of these two ways is not permanent , It can only exist relatively , Different models have different results .
Due to space limitation , This article mainly analyzes how to reduce oom_adj To reduce the value of APP The chance of being killed , as well as oom_adj How value is achieved ?
Next , We need to understand Android The rules by which the system reclaims processes in memory :
There are five main states for a process to be active while it is in memory : Foreground process 、 See the process 、 Service process 、 Background processes 、 Empty process , The process priority of these States is from high to low ,oom_adj Value from low to high ( stay ProcessList Definition ). then Android According to the current system resources and processes oom_adj Value to reclaim the corresponding process , Foreground processes are generally not recycled , Empty processes are the easiest to recycle , This kind of management rule is " According to legend " Of Low Memory Killer.
notes : priority 1 Represents the highest level , Of ordinary processes oom_adj>=0, System processes oom_adj<0, The system will match a certain segment according to the corresponding memory threshold oom_adj Value of the process . in addition ,oom_adj The value also increases as the physical memory is consumed , System processes will never be killed by the system .
Next, I will first analyze the mainstream in the market APP Anti killing method , Provide reference for my next plan , Please read on
APP The first stage of the process anti kill scheme : Open the front desk Service,“ Force you to ascend ”
take Service Set it as the front desk , The goal is to improve the process Service Of oom_adj value , To reduce the probability of being recycled by the system . The principle of the scheme is , By using startForeground() Method will be current Service Put it on the front desk to improve Service The priority of the . It should be noted that , Yes API Greater than 18 for startForeground() Method needs to pop up a visible notification , If you feel uncomfortable , Can open another Service Remove the notification bar , Its oom_adj The value has not changed .
Explain , There are also two techniques used here :
One is in onStartCommand Return in method START_STICKY, Its function is when Service The process is kill after , The system will try to recreate this Service, And will keep Service Is in the start state , But do not keep the passed Intent object ,onStartCommand Methods must be called again ;
Second, in onDestory Method , in other words , as long as Service When it was destroyed, it came to onDestory Here we will restart it .
Explain :
From what we know , One Service There is no independent process , It usually runs as a thread in the application process where it is located , And the application process name is consistent with the package name . If you want the specified components and applications to run in the specified process , It needs to pass android:process Property to create a process for it , therefore android:process=":daemon_service" Is to make DaemonService Run under the name “com.jiangdg.keepappalive:daemon_service” In progress ;android:enabled The function of attributes is Android Whether the system instantiates components in the application ;android:exported Property is used for the current component (Service) Whether it can be started by components in applications other than itself . Instant messaging development

test result :
Next , Let's observe KeepAppAlive Process oom_adj Value change .
First ,adb see KeepAppAlive Process number of the process :
E:\Android\StudioProject\KeepAppAlive>adb shell
[email protected]:/ $ su
[email protected]:/ # ps | grep jiangdg
APP The second stage of the process anti kill scheme : Monitor lock screen broadcast ,“ manufacture ‘1 Pixels ’ tragedy ”
Explain :
Java There are four levels of references to objects in : Strong citation 、 Soft citation 、 Weak reference 、 Virtual reference . here , We use weak references WeakReference To prevent memory leaks , To explain the problem , Let's take an example : There are two classes class A and class B, Instantiate these two classes respectively to get a,b, among a As an instance B The construction parameter passed in when , The code is as follows :
A a = newA();
B b = newB(a);
From these two lines of code ,a It's the object A References to ,b It's the object B References to , object B At the same time, it depends on the object A, object A And the object B A strong reference is formed between . When a=null when ,a Not pointing to object A, Usually , object A When it is not referenced by other objects, it will be GC Recycling , But because of B It also depends on objects A, object A It won't be GC Recycling , This causes memory leaks ( Unless b=null, object A And the object B Will be GC Recycle at the same time ). If you use weak references , object A Will only be WeakReference Depend on , When a=null when ,GC Will recycle it , This avoids memory leaks .
stay UI Interface architecture , Every Activity All contain a Window object , stay Android in Window Objects are usually made of PhoneWindow To achieve ,PhoneWindow Will a DecorView Set to the root of the entire application window View, It acts as the top-level view of the window interface , It encapsulates many methods of general operation windows ... Okay , Not far , Now that we know Window The object is in a Activity Position in , Here we go through getWindow How to get SinglePixelActivity Of Window object , Then set relevant properties for it , For example, the size of the form 、 Location 、 Coordinates, etc , To achieve the desired "1 Pixels " Interface effect .
Explain :
1)android:launchMode attribute : Is used to specify the activity Start mode of , There are four kinds in total , namely :
- standar Pattern , Each start activity Will create its instance , And add it to the top of the task stack ;
- singleTop Pattern , Each start activity If at the top of the stack activity No need to create , For the rest of the cases, create this activity Example ;
- singleTask Pattern , If it's activated activity Instances of exist on the stack , You don't need to create , Just put this activity Add to the top of the stack , And put the activity The above activity All instances pop;
- singleInstance Pattern : Will create the activity The instance is placed on a separate stack , The stack can only store this instance , And exists as a shared instance .
2)android:configChanges attribute : Used to capture changes in phone status , That is, when the mobile phone is in ( Such as switching between horizontal and vertical screens 、 The screen size ) The current active state will be saved and restarted when changing Activity, because SinglePixelActivity Shouldering the special mission of keeping alive , Use here android:configChanges attribute : prevent Activity restart , It just calls onConfigurationChanged(Configuration newConfig) To notify the change of mobile phone status ;
3)android:excludeFromRecents attribute : Used to control the SinglePixelActivity Do not show in the recent task list ;
4)android:finishOnTaskLaunch attribute : Used to mark when the user starts the application again (TASK) Whether to close the existing Activity Example ,false Means not to close ;
5)android:theme attribute : Is used to specify the Activity Show theme , Here we customize the theme SingleActivityStyle.
Monitor lock screen broadcast , The screen lock will SportActivity Put it on the front desk ( so ) :
Monitor lock screen broadcast , Turn on when locking the screen SinglePixelActivity(1 Pixels ):
APP The third stage of process anti kill scheme : Loop through a silent audio ," Create a Vajra body that is not bad "
For Samsung C9、Note4 And Huawei 4X Come on , Combined with the front desk Service And levitation interface (1 Pixels ) How to keep alive , When the user does not take the initiative to clean up or kill , test APP The effect of keeping alive is very good .
however , For huawei Mate8 Come on , The effect is still not satisfactory , Especially when using one click to clean up memory , test APP It's almost impossible to survive . then ," splash " But miraculously survived , You can't get rid of it with one click , Just when I can't think about it " The elder sister " when , One " nausea " The interface of appears in front of me . fuck ! See the red box below ," splash " Actually playing a silent music loop in the background , No wonder the vitality is so strong , But power consumption is also a lever .
ok , Not so much , This is just a study from the perspective of technology , After all, users are still very sensitive to power consumption , It's still a convergence point if you have to , Don't be so " Coquettish ", User experience is important , If you're not careful " Diarrhea " After you .
test result :
Here it is cmd Window use "ps | grep jiangdg" command , If the process exists in memory , Then print the process information ; If it doesn't exist , There is no information .
The test conditions of each model are as follows :
1) Huawei Mate8(Android 7.0): Will test APP In the background , The front desk Service In the black screen state 1 Be killed in minutes ,"1 Pixels " suspension Activity Test in black screen 2 Hours still live , The effect is OK . however , When the user cleans up recent apps with one click , Will be killed , When turned on in the background Serive When playing a silent audio loop , One click cleanup is still alive , Live in black screen mode in the background 12 hours ;
2) samsung C9(Android 6.0): Open the front desk Service and 1 Pixels ,KeepAppAlive Live in black background mode 9 Over hours , It seems that the native system is softer ; Start the background playing audio service , The user can clean up the recent application with one click and keep it alive ;
3) Huawei 4X(Android 6.0): The effect is the same C9;
4) samsung Note4(Android 5.0): The effect is the same C9.
notes :Mate8 Loop through a silent audio , When the user clicks one button to clean up the recent application ,KeepAppAlive Won't be killed , But if the user only chooses to clean KeepAppAlive when , Will also be killed , This is related to " splash " The effect of keeping alive is consistent .
边栏推荐
- JPA learning 1 - overview, JPA, JPA core annotations, JPA core objects
- HMS core discovery Episode 13 live broadcast Preview - building the real world in mobile games
- UE4 WebBrowser图表不能显示问题
- VR全景怎么赚钱?结合市场从两个方面客观分析下
- 普通人的生活准则
- Today's sleep quality record 79 points
- MySQL日志管理
- Analysis report on the "fourteenth five year plan" and development trend of China's engineering project management industry from 2022 to 2028
- How to resolve the 35 year old crisis? Sharing of 20 years' technical experience of chief architect of Huawei cloud database
- ArcGIS loads free online historical images as the base map (no plug-ins are required)
猜你喜欢

Hibernate learning 3 - custom SQL

openGauss内核:简单查询的执行

为什么生命科学企业都在陆续上云?

Solution of IP network broadcasting system in Middle School Campus - Design Guide for Campus Digital IP broadcasting system

Tongji and Ali won the CVPR best student thesis, lifeifei won the Huang xutao award, and nearly 6000 people attended the offline conference

canvas线条的动态效果

5G dtu无线通信模块的电力应用

信号完整性(SI)电源完整性(PI)学习笔记(二十五)差分对与差分阻抗(五)

VR全景制作的优势是什么?为什么能得到青睐?

5年,从“点点点”到现在的测试开发,我的成功值得每一个借鉴。
随机推荐
Scala IO writes data to a text file
∞符号线条动画canvasjs特效
What are the advantages of VR panoramic production? Why is it favored?
Current situation analysis and development trend prediction report of hesperidase industry in the world and China from 2022 to 2028
U.S. House of Representatives: digital dollar will support the U.S. dollar as the global reserve currency
Power application of 5g DTU wireless communication module
中低速航空航天电子总线概述
Annual salary of millions, 7 years of testing experience: stay at a fairly good track, accumulate slowly, wait for the wind to come
美国众议院议员:数字美元将支持美元作为全球储备货币
JPA学习1 - 概述、JPA、JPA核心注解、JPA核心对象
信号完整性(SI)电源完整性(PI)学习笔记(二十五)差分对与差分阻抗(五)
How does VR panorama make money? Based on the objective analysis of the market from two aspects
都2022年了,你还不了解什么是性能测试?
Enterprise data leakage prevention solution sharing
Nacos究竟是什么
Hibernate learning 2 - lazy loading (delayed loading), dynamic SQL parameters, caching
Tongji and Ali won the CVPR best student thesis, lifeifei won the Huang xutao award, and nearly 6000 people attended the offline conference
信号完整性(SI)电源完整性(PI)学习笔记(一)信号完整性分析概论
Printf redirection of serial port under sw4stm32 (SW4)
Number of bytes corresponding to common data types