Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize memory in Android

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge points about how to optimize memory in Android. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Memory leaks caused by unreleased references

1.1 memory leak caused by non-cancellation of registration

The memory leak of this kind of Android is more serious than that of pure java, because some other Android programs may refer to the objects of our Anroid programs (such as registering machine). Even though our Android program is over, other references still have references to an object of our Android program, and the leaked memory still cannot be garbage collected.

For example, example 1:

Suppose we want to monitor the phone service in the system for some information (such as signal strength, etc.) in the lock screen interface (LockScreen), we can define an object of PhoneStateListener in LockScreen and register it with the TelephonyManager service. For LockScreen objects, a LockScreen object is created when the lock screen interface needs to be displayed, and the LockScreen object is released when the lock screen interface disappears.

But if we forget to cancel our previously registered PhoneStateListener object when releasing the LockScreen object, it will cause the LockScreen to be unable to be garbage collected. If the lock screen interface continues to display and disappear, it will eventually cause OutOfMemory because a large number of LockScreen objects can not be recycled, making the system_process process hang up.

Although some system programs seem to cancel the registration automatically (not in time, of course), we should explicitly cancel the registration in our program, and all registrations should be cancelled at the end of the program.

1.2 memory leaks caused by non-cleaning of objects in the collection

We usually add references to some objects to the collection, and when we don't need the object, we don't clean up its references from the collection, so the collection gets bigger and bigger. If the collection is static, the situation is even more serious.

Memory leakage caused by the failure to close the resource object

Resource objects such as (Cursor,File files, etc.) often use some buffers, and when we are not using them, we should close them in time so that their buffers can reclaim memory in time. Their buffers exist not only within the java virtual machine, but also outside the java virtual machine. If we just set its references to null without turning them off, it will often cause a memory leak. Because some resource objects, such as SQLiteCursor (in the destructor finalize (), if we do not close it, it will switch close () off), if we do not close it, the system will close it when it is recycled, but this efficiency is too low. Therefore, when the resource object is not in use, you should call its close () function, close it, and then set it to null. Make sure that our resource object is turned off when our program exits.

The operation of querying the database is often carried out in the program, but there are often cases in which the Cursor is not closed after using it. If our query result set is relatively small, the memory consumption is not easy to be found, and memory problems will be reproduced only in the case of a large number of operations in normal time, which will bring difficulties and risks to future testing and problem troubleshooting.

Third, some bad codes lead to memory pressure

Some codes do not cause memory leakage, but they either do not release the unused memory effectively and timely, or apply for new memory frequently without making effective use of existing objects, which has a great impact on memory recovery and allocation, and is easy to force the virtual machine to allocate more memory to the application process, resulting in unnecessary memory expenditure.

3.1 MagneBitmap did not call recycle ()

When the Bitmap object is not in use, we should first call recycle () to free memory before it is set to null. Although recycle () from the source code point of view, calling it should immediately free the main memory of Bitmap, but the test results show that it does not immediately free memory. But I think it can still greatly accelerate the release of the main memory of Bitmap.

3.2.When constructing Adapter, no cached convertView is used

Taking the BaseAdapter of constructing ListView as an example, a total of methods are proposed in BaseAdapter:

Public View getView (int position, View convertView, ViewGroup parent) to provide ListView with the view objects that each item needs. Initially, ListView instantiates a certain number of view objects from BaseAdapter based on the current screen layout, and ListView caches these view objects. When scrolling up the ListView, the view object that was originally at the top of the list item is recycled and then used to construct the new lowest list item. This construction process is done by the getView () method, and the second parameter View convertView of getView () is the cached view object of list item (convertView is null if there is no view object in the cache at initialization).

From this, we can see that if we do not use convertView, but re-instantiate a View object in getView () each time, it will waste time, cause memory problems, and add pressure to garbage collection. If garbage collection is too late, the virtual machine will have to allocate more memory to the application process, resulting in unnecessary memory expenses. The process of ListView recycling list item's view object can be seen as follows:

View plaincopy to clipboardprint?

Android.widget.AbsListView.java-> void addScrapView (View scrap) method.

In the development of android, it is necessary to always allocate the main memory and garbage collection, because the memory allocated by the system for each dalvik virtual machine is limited. In the G1 of google, the heap size allocated is only 16m, and the later machines are generally 24m, which is really pitiful. This requires us to pay attention to it all the time in the development process. Don't cause OOM errors because of your own code problems.

Memory management for JAVA:

As we all know, the android application layer is developed by java, and android's davlik virtual machine is similar to jvm, except that it is register-based. Therefore, to understand the memory management of android, it is necessary to understand the memory allocation and garbage collection mechanism of java.

In java, memory is allocated to objects through the new keyword, and the release of memory is reclaimed by the garbage collector (GC). Engineers do not need to explicitly manage memory during development. But it is possible to waste a lot of memory before you know it, resulting in the java virtual machine spending a lot of time on garbage collection and, more seriously, JVM's OOM. Therefore, it is still necessary for java engineers to understand JAVA's memory allocation and garbage collection mechanisms.

The problems are listed below. Click detail to enter, and you will list the detailed codes that may have problems:

File:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/ksohtml/wps_clip_image-32625.png

File:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/ksohtml/wps_clip_image-21158.png

Summary

Both java and android should understand the memory allocation and garbage collection mechanism. It is very difficult for engineers to write code without bad code. The key is how to troubleshoot Android memory optimization when something goes wrong.

I. the memory mechanism of Android

Android programs are written in the Java language, so the memory management of Android is similar to that of Java. Programmers allocate memory to objects through new, and all objects allocate space in the java heap; however, object release is done by the garbage collector. The memory mechanism in java Candle + is "who pollutes, who treats it". It is more humanized and has hired a special cleaner (GC) for us.

So how can GC confirm that an object has been abandoned? Java adopts the principle of directed graph. Java considers the reference relationship as the directed edge of the graph, and the directed edge points from the referrer to the reference object. Thread objects can be used as the starting vertices of a directed graph, which is a tree starting from the starting vertices. The objects that can be reached by the root vertices are valid objects, and GC will not recycle these objects. If an object (connected subgraph) and this root vertex are not reachable (note that the graph is a directed graph), then we think that this (these) objects are no longer referenced and can be recycled by GC.

2. Memory overflow of Android

How does the memory overflow of Android occur?

Android's virtual machine is a register-based Dalvik, and its heap size is usually 16m, and some machines are 24m. Therefore, the memory space we can use is limited. If our memory footprint exceeds a certain level, there will be an OutOfMemory error.

Why is there not enough memory? I think there are two main reasons:

Due to the mistakes of our program, we keep the references of some resources (such as Context) for a long time, resulting in memory leakage and resources not being released.

Multiple objects that consume too much memory (such as Bitmap) are saved, causing the memory to exceed the limit.

III. Evil static

Static is a keyword in Java, and when you use it to modify a member variable, the variable belongs to the class, not an instance of the class. So variables modified with static have a long life cycle, and should be treated with caution if you use it to refer to instances that consume too much resources (in the case of Context).

SBackground is a static variable, but we find that we don't explicitly save a reference to Contex, but when Drawable connects to View, Drawable sets View as a callback, and because View contains a reference to Context, we actually still keep a reference to Context. The chain of references is as follows:

Drawable- > TextView- > Context

So, in the end, the Context was not released, and a memory leak occurred.

How can we effectively avoid this kind of citation?

Try to avoid static member variables referencing instances that consume too much resources, such as Context.

Context uses Application Context as much as possible, because Application's Context has a long life cycle and there is no memory leak when referencing it.

Use WeakReference instead of strong references. For example, you can use WeakReference mContextRef

The details of this section can also be found in the Article section of the Android documentation.

Fourth, it is all caused by the thread.

Threads are also an important source of memory leaks. The main reason for memory leaks caused by threads is the uncontrollable life cycle of threads. Let's consider the following code.

Some people like to use the AsyncTask provided by Android, but in fact, the problem of AsyncTask is more serious. Thread only occurs when the run function does not end. However, the internal implementation mechanism of AsyncTask is the use of ThreadPoolExcutor, and the life cycle of Thread objects generated by this class is uncertain and can not be controlled by the application, so if AsyncTask is an internal class of Activity, it is more likely to have memory leaks.

In fact, the problem with threads is not just memory leaks, but also catastrophic problems.

5. Cursor with strange whereabouts

Cursor is a class that manages the data set obtained by Android after querying data. Under normal circumstances, if the amount of data obtained by the query is small, there will be no memory problems, and the virtual machine can guarantee that Cusor will eventually be released.

However, if the data volume of Cursor is large, especially if there is Blob information in it, you should ensure that the memory occupied by Cursor is released in time, rather than waiting for GC to deal with it. And Android obviously prefers programmers to manually drop Cursor close, because in the source code we find that if we wait for the garbage collector to collect, it will give the user an error message.

In one case, we can't turn off Cursor directly, which is what happens in CursorAdapter, but note that CursorAdapter doesn't automatically turn off Cursor at the end of Acivity, so you need to close it manually in the onDestroy function.

These are all the contents of the article "how to optimize memory in Android". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report