Android performance optimization to fix memory leaks in the game (java layer)

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 :

insert image description here
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.
insert image description here
Holding relationship:
context.getContentResolver()注册ContentObserver-->Activity的匿名内部类Listener -->splashActivity。
insert image description here
Solution : set the anonymous external class, set the external class or move it to another class to set.
insert image description here

2. The orientation of the screen causes the Activity to be held

The memory leak caused by the screen selection of WXPayEntryActivity:
insert image description hereView the source code in ActivityThread:
[picture]
Then continue, and see what will be called:
insert image description here
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:
insert image description here
solution : addandroid:screenOrientation="sensorLandscape"

insert image description here

3. Activity is held by the system class as context

insert image description here
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;

Guess you like

Origin blog.csdn.net/hexingen/article/details/131921647