In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of what is the cause of Android memory leak, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article on the cause of Android memory leak. Let's take a look.
In Android development, Context is the most likely to cause memory leaks. Activity's Context, for example, contains a large number of memory references, such as View Hierarchies and other resources. Once Context is leaked, it also means leaking all the objects it points to. Android machine memory is limited, too many memory leaks can easily lead to OOM.
Detecting logical memory leaks requires subjective judgment, especially the life cycle of the object is not clear. Fortunately, Activity has a clear life cycle and it is easy to identify the cause of the leak. Activity.onDestroy () is seen as the end of Activity's life, and programmatically, it should be destroyed, or the Android system needs to reclaim the memory. Android reclaims invisible Activity when there is not enough memory.
If this method is finished, there is still a strong reference holding the Activity in the stack, and the garbage collector cannot mark it as reclaimed memory, which we intended to reclaim!
The result is that Activity lives outside its life cycle.
Activity is a heavyweight object and should be handled by the Android system. However, logical memory leaks always occur inadvertently. (translator's note: an Activity has been tried to cause a 20m memory leak). In Android, there are only two traps that can lead to potential memory leaks:
Static variable of the global process (process-global). This monster, ignoring the state of the application, holds a strong quote from Activity.
Threads that live outside the Activity lifecycle. There is no clear strong reference to Activity.
Check to see if you have encountered the following situations.
Static Activities
A static Activity variable is defined in the class to assign the currently running Activity instance to this static variable.
If this static variable is not emptied after the end of the Activity life cycle, it results in a memory leak. Because the static variable runs through the life cycle of the application, the leaked Activity will always exist in the application process and will not be reclaimed by the garbage collector.
Static Activity activity; void setStaticActivity () {activity = this;} View saButton = findViewById (R.id.sa_button); saButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {setStaticActivity (); nextActivity ();}})
Memory Leak 1-Static Activity
Static Views
A similar situation can happen in singleton mode, and if Activity is often used, it is practical to keep an instance in memory. As mentioned earlier, forcing an extension of the life cycle of an Activity is quite dangerous and unnecessary, and should not be done in any case.
Special case: if a View initialization consumes a lot of resources and remains the same during an Activity life cycle, it can be turned into a static and loaded into the view tree (View Hierachy), like this, when the Activity is destroyed, resources should be released. (translator's note: there is no memory released in the sample code, just set this static view to null, but this static view method is still not recommended.)
Static view; void setStaticView () {view = findViewById (R.id.sv_button);} View svButton = findViewById (R.id.sv_button); svButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {setStaticView (); nextActivity ();}})
Memory Leak 2-Static View
Inner Classes
Go on, suppose there is an inner class in Activity, which improves readability and encapsulation. If we create an inner class and hold a reference to a static variable, congratulations, the memory leak is not far from you.
Private static Object inner; void createInnerClass () {class InnerClass {} inner = new InnerClass ();} View icButton = findViewById (R.id.ic_button); icButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {createInnerClass (); nextActivity ();}}))
Memory Leak 3-Inner Class
One of the advantages of inner classes is that they can access external classes. Unfortunately, the reason for memory leaks is that internal classes hold strong references to instances of external classes.
Anonymous Classes
Similarly, anonymous classes maintain references to external classes. So memory leaks can easily happen when you define anonymous AsyncTsk in Activity.
. When an asynchronous task executes a time-consuming task in the background, the Activity is unfortunately destroyed, and the Activity instance held by AsyncTask will not be reclaimed by the garbage collector until the asynchronous task ends.
Void startAsyncTask () {new AsyncTask () {@ Override protected Void doInBackground (Void...) Params) {while (true);}} .execute ();} super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); View aicButton = findViewById (R.id.at_button); aicButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {startAsyncTask (); nextActivity () })
Memory Leak 4-AsyncTask
Handler
By the same token, define an anonymous Runnable and execute it with the anonymous class Handler. The Runnable inner class holds an implicit reference to the external class and is passed to Handler's message queue MessageQueue, and the Activity instance is not destroyed until the Message message is processed, resulting in a memory leak.
Void createHandler () {new Handler () {@ Override public void handleMessage (Message message) {super.handleMessage (message);}} .postdelayed (new Runnable () {@ Override public void run () {while (true);}}, Long.MAX_VALUE > > 1) } View hButton = findViewById (R.id.h_button); hButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {createHandler (); nextActivity ();}})
Memory Leak 5-Handler
Threads
Once again, we use Thread and TimerTask to show memory leaks.
Void spawnThread () {new Thread () {@ Override public void run () {while (true);}} .start ();} View tButton = findViewById (R.id.t_button); tButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {spawnThread (); nextActivity () })
Memory Leak 6-Thread
TimerTask
Any instance of an anonymous class, whether in the worker thread or not, will hold a reference to Activity, resulting in a memory leak.
Oid scheduleTimer () {new Timer () .schedule (new TimerTask () {@ Override public void run () {while (true);}}, Long.MAX_VALUE > > 1);} View ttButton = findViewById (R.id.tt_button) TtButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {scheduleTimer (); nextActivity ();}})
Memory Leak 7-TimerTask
Sensor Manager
*. System services can be obtained through Context.getSystemService (int name). These services work in their own processes, helping applications handle background tasks and hardware interactions. If you need to use these services, you can register the listeners, which will cause the service to hold a reference to the Context, which will cause a memory leak if the listeners are not unregistered when the Activity is destroyed.
Void registerListener () {SensorManager sensorManager = (SensorManager) getSystemService (SENSOR_SERVICE); Sensor sensor = sensorManager.getDefaultSensor (Sensor.TYPE_ALL); sensorManager.registerListener (this, sensor, SensorManager.SENSOR_DELAY_FASTEST);} View smButton = findViewById (R.id.sm_button) SmButton.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {registerListener (); nextActivity ();}})
This is the end of the article on "what is the cause of the Android memory leak?" Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "what is the cause of Android memory leak". If you want to learn more knowledge, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.