How to avoid memory leakage by handler in kotlin

preface:

The philosophy teacher said that looking at things is nothing more than understanding what it is, why and how to do it

So, first, let's take a look at what a "memory leak" is

A passage from Baidu: the space dynamically opened with the dynamic storage allocation function is not released after use, resulting in occupying the memory unit all the time. Until the end of the program.

Is it a bit awkward? In other words, one day you went to a restaurant for dinner. A fat man finished his meal, but he occupied a table. However, now a group of people are waiting for dinner. As a result, the dead fat man didn't leave until the restaurant closed.

In this example, the restaurant table is like memory space. The fat man is a function, and eating is the event executed.

Now, what we have to do is to drive away the dead fat man.

Handler is often used in Android development. If you are not careful, you will fall into the problem of memory leakage. Recently, a kotlin software is being developed to solve the problem of memory leakage of handler

Problem analysis:

At the time of finish (), the message has not been processed. The message holds the handler and the handler holds the activity. This prevents the GC from recycling the activity, resulting in memory leakage. The correct way to write it is to use explicit references, static internal classes and external classes. Use weak reference WeakReference. Finally, cancel the message and runnable of the handler object when the activity calls ondestroy()

Core code:

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

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
分享
二维码
< <上一篇
下一篇>>