The memory OOM of the game is getting more and more bugly, so the memory has been optimized recently. Starting from the memory optimization of the java layer, the memory snapshot was obtained through LeakCannary or adb shell, and several memory leaks were found.
1. The singleton class holds the Activity :
Looking at the memory snapshot, the splash screen activity (including reference objects) can reclaim 3.8M of memory;
LeakCannary's memory analysis also proves the memory size occupied by this object, holding 1380 objects.
Holding relationship:
context.getContentResolver()注册ContentObserver-->Activity的匿名内部类Listener -->splashActivity。
Solution : set the anonymous external class, set the external class or move it to another class to set.
2. The orientation of the screen causes the Activity to be held
The memory leak caused by the screen selection of WXPayEntryActivity:
View the source code in ActivityThread:
Then continue, and see what will be called:
open WeChat is displayed on a vertical screen, while the game is displayed on a horizontal screen, so when the WeChat interface is closed, it will go to the game When an Activity is created in the process, the screen needs to be adjusted, and overrideApplicationDisplayAdjustments()
correction will be called.
Then check the mobile phone system and find that the screen setting is automatic rotation.
Let's check the screen configuration of WXPayEntryActivit is the default:
solution : addandroid:screenOrientation="sensorLandscape"
3. Activity is held by the system class as context
The Activity on the advertisement page is held by GestureBoostManager. The solution is to use Application as context to obtain system classes.
Suggestions :
- Try to avoid holding Activity, try to use Application (except dialog);
- Use anonymous inner classes in Acitivity (avoid: new Listener), etc., and remove them in Ondestory() to avoid memory leaks caused by anonymous inner classes holding Activity
- Avoid setting the properties related to the Activity or the object of the held activity to static to avoid memory leaks;