当前位置:网站首页>[answer] if the app is in the foreground, the activity will not be recycled?
[answer] if the app is in the foreground, the activity will not be recycled?
2022-07-07 17:44:00 【QXXXD】
Understanding after conversion : Single process scenario ,Activity It can only be recycled because the process is recycled by the system .
It doesn't feel right ? Because a long time ago , I have encountered such a scene :
App Open multiple Activity, Then hang the mobile phone aside , After a while ( The screen is always on ), Click back , Previous Activity blank , Then reload .
App reception , Not at the top of the stack Activity But was killed , But the process is still alive , If that's the case , It's a little different from the above understanding .
Immediately write a code to verify , The general process is as follows :
Write a parent class Activity, Lifecycle callback plus log printing , Then open a Activity, Contains a button , Click to open multiple Activity, Add a button to the last one , Click to apply for a larger ByteArray To simulate memory allocation , See if the memory will be recycled when it is insufficient Activity.
The test results are as follows :
App Would rather OOM, And unwilling to recycle Activity, Add by magic android:largeHeap=“true” , Results the same .
em… Did I remember wrong ???
wait !!! I seem to have confused two things : There is not enough memory available in the system
and There is not enough memory available for the application
.
0x1、 There is not enough memory available in the system
LMK Mechanism
Android In the system , The life cycle of a process is controlled by the system , In consideration of experience and performance , stay APP Click on the Home Key or Back Fallback operation , It won't really kill APP, The process still exists in memory , So next time start this APP Can be faster . As the system runs longer , open APP More and more , The number of processes in memory increases , The available memory of the system will be less and less . To do , You can't let users kill the process by themselves , So the system has a set Recycling mechanism , When the available memory of the system reaches one threshold , The system will Process priority To kill part of the process , Free memory for subsequent startup APP Use .
Android This set of recycling mechanism , Is based on Linux Kernel OOM Improved rules , It's called Low Memory Killer
, abbreviation LMK.
threshold & Kill who
Through the following two documents , Different mobile phone values may be different , With my master machine The charm of blue E2 For example (Android 11 Of Mix2S I've been saying that I don't have permission to open this file ):
# /sys/module/lowmemorykiller/parameters/minfree
# Company :Page page ,1Page = 4KB
18432,23040,27648,46080,66560,97280
# /sys/module/lowmemorykiller/parameters/adj
0,58,117,176,529,1000
Android The system will maintain one for each process adj( priority )
:
- Android 6 And formerly known as :
oom_adj
, Range of values :[-17,16],LMK To convert *1000/17 - Android 7 Later called :
oom_score_adj
, Range of values :[-1000,1000]
then , The values of the above two files , In fact, it corresponds one by one , such as :
66560 * 4 / 1024 = 260MB → When the available memory of the system is reduced to 260MB when , Will kill adj Greater than 529 The process of ;
18432 * 4 / 1024 = 72MB → When the available memory of the system is reduced to 72MB, kill ajd Greater than 0 The process of ;
adj What do you think
View directly from the command line :
You can see ,adj It's dynamic , When App When the state and the life cycle of the four components change , Will change its value . common ADJ The levels are as follows :
- NATIVE_ADJ → -1000,init process fork Coming out native process , Not subject to system Control and control ;
- SYSTEM_ADJ → -900,system_server process ;
- PERSISTENT_PROC_ADJ → -800, System persistent process , Usually not killed , Kill or Carsh The system will also restart ;
- PERSISTENT_SERVICE_ADJ → -700, Associated with a system or persistent process ;
- FOREGROUND_APP_ADJ → 0, Foreground process ;
- VISIBLE_APP_ADJ → 100, See the process ;
- PERCEPTIBLE_APP_ADJ → 200, Perceptible process , Such as background music playing ;
- BACKUP_APP_ADJ → 300, perform bindBackupAgent() Backup process of process ;
- HEAVY_WEIGHT_APP_ADJ → 400, Heavyweight processes ,system/rootdir/init.rc Set in file ;
- SERVICE_ADJ → 500, Service process ;
- HOME_APP_ADJ → 600,Home process , The type is ACTIVITY_TYPE_HOME Application , Such as Launcher;
- PREVIOUS_APP_ADJ → 700, Last used by the user App process ;
- SERVICE_B_ADJ → 800,B List Medium Service;
- CACHED_APP_MIN_ADJ → 900, Invisible process Of adj minimum value ;
- CACHED_APP_MAX_ADJ → 906, Of invisible processes adj Maximum ;
- UNKNOWN_ADJ → 1001, Generally refers to the process to be cached , Unable to get deterministic value ;
About ADJ The detailed algorithm analysis of calculation can be seen Gityuan The bosses :《 Reading Android Process priority ADJ Algorithm 》, A lot of dry goods , By the way, we can find a way to keep the process alive from the summary :
- UI Process and Service Process separation , contain Activity Of Service process , As soon as you enter the backstage ADJ>=900, It may be recycled by the system at any time , If separated ADJ=500, Reduced likelihood of being killed , In particular, the system allows self starting service processes , Must do UI Separate , Avoid consuming large memory ;
- We really need applications that users can perceive , call startForegroundService() Enable front desk service ,ADJ=200;
- In process Service Finish work , Be sure to actively call stopService or stopSelf To stop the service , Avoid using memory , Waste system resources ;
- Don't bind to other processes for a long time service perhaps provider, Release immediately after each use , Avoid other processes resident in memory ;
- APP The interface should be implemented onTrimMemory() and onLowMemory(), according to TrimLevel Appropriately release the unnecessary memory in the callback method , This interface will be called back when the system memory is tight , Reduce the frequency of system jamming and killing process ;
- More efforts should be made to optimize memory , identical ADJ Level , The system will give priority to killing processes that occupy memory ;
ask : Can you put your own App Of ADJ Value is set to -1000, Make it immortal ? answer : Can not be , Want to have root Permission can be modified adj, And the phone is still restored after being restarted .
It's a little far , Back to the question :
When the system is low on memory , It will directly check and kill processes in the kernel layer , Not in Framework Layer also tells you which one to recycle Activity.
So at the system level , Single process scenario ,Activity It can only be recycled because the process is recycled by the system , There is nothing wrong with this sentence , But not necessarily at the application level .
0x2、 There is not enough memory available for the application
APP process ( virtual machine ) The memory allocation of is actually right Allocation and release of heap , For the memory control of the whole system , One will be set for each application Heap limit threshold , If the application uses memory close to the threshold, it also attempts to allocate memory , It is easy to cause OOM.
Of course , Not so stupid , And the developer himself is APP Reclaim memory in , The virtual machine comes with GC, There is no specific recycling algorithm for de scrolling
Assuming that the application memory is insufficient, it will really be recycled Activity, Then how to design ? One solution is as follows :
When app starts , Open a sub thread , Regularly poll whether the current available memory exceeds the threshold , If more than, kill Activity
Then come and follow Android Is it designed like this ?
Activity Recycling mechanism
Follow the application startup entry :ActivityThread → main()
Follow me attach():
It's very similar here ,run() Middle computation : Used memory > 3/4 Maximum memory , Is executed releaseSomeActivities(), Follow me :
therefore getService() Yes, I got IActivityTaskManager.aidl Interface , The concrete implementation class is ActivityTaskManangerService:
Keep going : RootActivityContainer → releaseSomeActivitiesLocked():
Follow me :WindowProcessController → getReleaseSomeActivitiesTasks()
Then go down to release Activity The code of :ActivityStack → releaseSomeActivitiesLocked()
Specific how to release , I won't follow you anymore , Then follow how to monitor ~
Memory monitoring mechanism
Follow back :BinderInternal.addGcWatcher()
You may be a little confused here , But when you understand it, you will feel wonderful :
virtual machine GC Will kill WeakReference The object of , Before freeing memory , Will call the object finalize(), And here is a new WeakReference example . The next time GC, I will go through the code here again , Tut tut tut , It is much more efficient than polling
Here we are , Insufficient application memory recycling Activity The process is probably clear , Then you can write a code to verify whether it is true .
Demo verification
Try two first Task Of :
Pages that simulate memory allocation , And then keep going ~
Would rather OOM, Nor recycle , Try three ~
good heavens ,onDestory() 了 , Press Back Go back to these pages , I found it gone onCreate(), That is, recycled , Then try four cases :
Sure , Only one at a time Task, This is the end of the verification ~
0x3、 Conclusion
- When the system is low on memory , Check and kill directly in the kernel layer ( Recycling ) process , It doesn't consider which one to recycle Activity;
- When the process is out of memory , If this process Activity Task Count >= 3 And Use more memory than 3/4, Would be right invisible Task To recycle , Every time you recycle 1 individual Task, The recovery time is each time gc;
At the end of the article
I have summed up some Android Core knowledge points , And some of the latest big factory interview questions 、 Knowledge brain map and video data analysis .
Needed Directly click on the small card at the end of the text to receive ! I'll share it with you for free , I hope we can go down together in the future .( Thank you for your support , You need to get it yourself )
Android Study PDF+ Architecture video + Interview document + Source notes
List of partial data :
- 330 page PDF Android Learning core notes ( contains 8 Large plate )
- Android The learning system corresponds to the video
- Android Advanced systems correspond to learning materials
- Android BAT Interview questions of Dachang ( With resolution )
边栏推荐
猜你喜欢
Deep learning machine learning various data sets summary address
Use onedns to perfectly solve the optimization problem of office network
toast会在程序界面上显示一个简单的提示信息
Examen des lois et règlements sur la sécurité de l'information
Functions and usage of imageswitch
Target detection 1 -- actual operation of Yolo data annotation and script for converting XML to TXT file
mui侧边导航锚点定位js特效
做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
Functions and usage of serachview
使用popupwindow創建对话框风格的窗口
随机推荐
L1-025 正整数A+B(Lua)
Target detection 1 -- actual operation of Yolo data annotation and script for converting XML to TXT file
深入浅出【机器学习之线性回归】
toast会在程序界面上显示一个简单的提示信息
Alertdialog create dialog
基于百度飞浆平台(EasyDL)设计的人脸识别考勤系统
Define menus using XML resource files
字符串 - string(Lua)
本周小贴士#134:make_unique与私有构造函数
第1章CRM核心业务介绍
【网络攻防原理与技术】第7章:口令攻击技术 第8章:网络监听技术
Functions and usage of ratingbar
青年时代历练和职业发展
Functions and usage of imageswitch
【可信计算】第十三次课:TPM扩展授权与密钥管理
Enum + Validation 的个人最佳实践 demo 分享
第2章搭建CRM项目开发环境(搭建开发环境)
MySQL index hit level analysis
DatePickerDialog and trimepickerdialog
mui侧边导航锚点定位js特效