Talk about Android memory leak

Memory leak: it refers to that the memory is not recovered in time by GC, resulting in excessive memory occupation, resulting in program crash, which is often referred to as oom. 1、 Static, let's look at the following code first

Such code is very common in projects. If you are more careful, you should find the problem there. The context application is held in the helper, and the dbhelper is global. That is, when a dbhelper is used in an activity, even if the activity exits, the activity cannot be recycled by the GC, resulting in the activity always residing in memory. This solution is also relatively simple. The code is as follows

Just change the context to ApplicationContext (), because ApplicationContext itself is global. 2、 Non static inner class and handler, let's take a look at a piece of code

We know that the non static internal class will hold the reference of the external class. At this time, the handler here holds the reference of the external activity. When we perform asynchronous time-consuming operations in the internal class of the activity, if our activity is finished and the asynchronous task does not end, our activity object will not be recycled by GC in time, This causes memory problems. Such a problem is also very simple to solve

Most of the memory problems are caused by the unfortunate processing of the object life cycle. When using an object, we need to carefully study the object life cycle. When processing some objects that occupy a large amount of memory and have a long life cycle, the application uses soft references to process them and close unused resources in time.

The above is the whole content of this article. I hope it will be helpful to your study.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>