Although I have been studying Android for more than a year in college and can already complete some requirements, I should not be very familiar with the underlying knowledge and some concepts in Android. I plan to take this opportunity during the long holiday to familiarize myself with them.
Android Memory Leaks#
Memory leaks refer to the situation where variable references that can no longer be accessed are saved, causing the garbage collector to be unable to reclaim memory.
In other words:
In Java, the lifecycle of some objects is limited. When they have completed specific logic, they will be reclaimed. However, if an object is still referenced by other objects when it should have been reclaimed in its lifecycle, it will cause a memory leak.
Specific example:
public class LeakAct extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aty_leak);
test();
}
public void test() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}z
}
}).start();
}
}
test is a non-static inner class. When we finish, this instance will not be destroyed, and the GC mechanism will not perform garbage collection on this instance because anonymous inner classes and non-static inner classes hold strong references to the outer class. In other words, test holds a strong reference to the outer activity, and the while loop inside the thread is an infinite loop, so the thread will not stop, and the strong reference to the outer activity will not disappear. This causes a memory leak.
Solution
- Convert the inner class to a static inner class;
- If there is a strong reference to an attribute in the Activity, change the reference to a weak reference;
- When the Activity executes onDestroy, end these time-consuming tasks if the business allows.
Android Memory Overflow#
Memory overflow refers to the situation where an app requests memory from the system that exceeds the maximum threshold, and the system will not allocate additional space, resulting in memory overflow.
- A typical example is loading multiple large images, which leads to memory exhaustion. You can compress the quality or size of the images appropriately.
- When a certain interface has a memory leak and you repeatedly enter this interface, new objects will continue to be created but cannot be reclaimed, eventually leading to memory exhaustion and causing a memory overflow.