Android Memory leakage

Source: Internet
Author: User

Android Memory leakage
Avoid Android Memory leakage
Android applications are limited to run on 16 MB stacks, at least on T-Mobile G1. For mobile phones, this is a lot of memory, but for some developers, this is relatively small. Even if you do not plan to use all the memory, you should use as little memory as possible to ensure that other applications can run. Android retains more applications in the memory. for users, inter-program switching can be faster. As part of my (English author) work, I investigated the memory leakage of Android applications and found that most of these memory leaks were caused by the same errors, namely: references the Context for a long time.
In Android, Context is often used for many operations, and more often it is to load and access resources. This is why all widgets accept a Context parameter in their constructor. In a normal Android Application, you can see two Context types: Activity and Application. Generally, in the class and method that requires a Context, the first type is often introduced:

@Overrideprotected void onCreate(Bundle state) {  super.onCreate(state);  TextView label = new TextView(this);  label.setText(Leaks are bad);  setContentView(label);}
This means that the View has reference to the entire Activity and all the content of the Activity itself; generally, the whole View level and all its resources. Therefore, if you "leak" Context ("leak" means that you keep a reference to prevent GC garbage collection), you will leak a lot of memory. If you are not careful enough, it is easy to leak an Activity.
When the screen direction changes, the system will usually destroy the current Activity, create a new Activity, and save its status. When the system does this, Android reloads the application UI from the resource. Suppose the application you write has a large bitmap, and you don't want to reload it every time you rotate it. Here is the simplest way to save it in a static field:
private static Drawable sBackground;  @Overrideprotected void onCreate(Bundle state) {  super.onCreate(state);    TextView label = new TextView(this);  label.setText(Leaks are bad);    if (sBackground == null) {    sBackground = getDrawable(R.drawable.large_bitmap);  }  label.setBackgroundDrawable(sBackground);    setContentView(label);}

This code is very efficient, but it is extremely incorrect at the same time. During the first screen direction switch, it exposes the Activity created at the beginning. When a Drawable is appended to a View, the View sets it as a callback to the Drawable. The code snippet above means that Drawable has a reference to TextView, while TextView has reference to Activity (Context type). In other words, drawable has more object references (dependent on your code ).

This is one of the examples of the most vulnerable to Context leakage. You can check how the unbindDrawables () method is searched in the source code of Home Screen: when the Activity is destroyed, set the callback of the stored Drawable to null. Interestingly, there are a series of Context leaks, which are very bad. These situations will make the application quickly run out of memory.


There are two simple methods to avoid Memory leakage related to Context. The most obvious way is to avoid extending the Context beyond its own range. The static references provided in the above example code, as well as internal classes and their external class implicit references are also very dangerous. The second solution is to use the Context type of Application. This Context has the same long life cycle as the application and does not depend on the Activity life cycle. If you want to save a long object and need a Context, remember to use the Application object. You can easily obtain the Application object by calling Context. getApplicationContext () or Activity. getApplication.

To avoid Memory leakage related to Context, remember the following:

1. Do not retain reference to Context-Activity for a long time (Make sure that you have the same lifecycle as Activity when referencing Activity)

2. Try to use Context-Application instead of Context-Activity.

3. If you do not want to control the lifecycle of internal classes, you should avoid using non-static internal classes in the Activity. Instead, you should use static internal classes, create a weak reference to the Activity. The solution to this problem is to use a static internal class with the WeakReference of the external class, as shown in ViewRoot and its Winner class.

4. GC (garbage collection) cannot solve the memory leakage problem



Android (Java) in the common easy to cause memory leakage of bad code: Reprinted from http://mzh3344258.blog.51cto.com/1823534/895093

Android is mainly used in embedded devices. embedded devices generally do not have high configurations due to some well-known restrictions, especially limited memory. If the code we wrote contains too many improper memory usage, it will inevitably make our devices run slowly or even crash. To ensure secure and fast running of Android applications, each Android application runs with a proprietary Dalvik Virtual Machine instance, which is evolved from the Zygote service process, that is to say, every application runs in its own process (question 1: How does Pony know that it runs in its own process? The answer will be detailed below ). On the one hand, if the program encounters a memory leak during the running process, it will only kill its own process without affecting other processes (if the system process such as system_process has a problem, will cause the system to restart ). On the other hand, Android allocates different memory usage ceilings for different types of processes. If the memory used by the application process exceeds the upper limit, the system will regard it as a memory leak and thus be killed.

The following pony explains Question 1: "Every application runs in its own process: "when a program is started for the first time, Android will start a LINUX Process and a main thread. By default, all components of the program will run in the process and thread ."~ Pai_^ O_O !!!

In addition, Android assigns a LINUX User to each application. Android will try to keep a running process. When the memory resources are insufficient, Android will try to stop some processes and release enough resources for other new processes to use, it can also ensure that the current process being accessed by the user has enough resources to respond to the user's events in a timely manner. Android judges the importance of a process based on the component category and component Status in the process. Android first stops unimportant processes. There are five levels of importance from high to low: foreground processes, visible processes, service processes, background processes, and empty processes (here we will look at the concept)

There is also a small extension: when a program is started for the first time, Android will start a corresponding Main Thread at the same time. The Main Thread is mainly responsible for processing UI-related events, for example, the user's key events, the user's access to the screen events and Screen Drawing events, and the relevant events are distributed to the corresponding components for processing. Therefore, the main thread is often called the UI thread. When developing Android applications, you must follow the single-thread model principle: Android UI operations are not thread-safe and must be executed in the UI thread. The Android UI is Single-threaded. To avoid dragging the GUI, some time-consuming objects should be handed over to independent threads for execution. If the background thread executes the UI object, Android sends an error message CalledFromWrongThreadException. In the future, you must know what is going on when such an exception is thrown!


Examples of causes of Memory leakage:

1. The cursor is not closed when the database is queried.

The program usually queries the database, but it often does not close after using the Cursor. If our query result set is small, memory consumption is not easy to find. Memory problems can be found only when a large number of operations are performed at a regular time, this will cause difficulties and risks for future testing and troubleshooting. The example code is as follows:

Cursor cursor = getContentResolver (). query (uri ...); if (cursor. moveToNext ()){......} corrected sample code: Cursor cursor = null; try {cursor = getContentResolver (). query (uri ...); if (cursor! = Null & cursor. moveToNext () {...} finally {if (cursor! = Null) {try {cursor. close ();} catch (Exception e) {// ignore this }}}

2. When constructing the Adapter, the cached convertView is not used

Taking the BaseAdapter used to construct the ListView as an example, the methods in BaseAdapter are described as follows:

Public View getView (int position, View convertView, ViewGroup parent)

To provide ListView with the view object required by each item. Initially, the ListView will instantiate a certain number of view objects from the BaseAdapter based on the current screen layout, and the ListView will cache these view objects. When you scroll up the ListView, the view object originally located in the top list item will be recycled and then used to construct the bottom list item that appears. This construction process is completed by the getView () method, getView () the second View convertView parameter is the view object of the cached list item. (convertView is null if no view object is cached during initialization ).

It can be seen that if we do not use convertView, but re-instantiate a View object in getView () every time, it will waste time and cause memory garbage, increasing the garbage collection pressure, if garbage collection is too late, the virtual machine will have to allocate more memory to the application process, causing unnecessary memory consumption.

3. When the Bitmap object is not in use, the recycle () call is not released in time.

If a Bitmap object occupies memory, when it is not in use, you can call Bitmap. recycle () to reclaim the memory occupied by pixels of this object.

4. The object reference is not released in time.

For example, the Context or other custom objects transmitted between two activities must be released immediately after use: Activity = null; Context = null; Object = null; if yes, notify the System to recycle the objects after they are released: System. gc (); this is the best!


5. Memory leakage caused by registration not canceled

This Android Memory leakage is more serious than pure java Memory leakage, because some other Android programs may reference the objects of our Anroid program (such as the registration mechanism ). Even though our Android program has ended, other reference programs still reference an object of our Android program, and the leaked memory cannot be recycled.

For example

Suppose we want to listen to the telephone service in the system in the LockScreen interface to obtain some information (such as signal strength), we can define a PhoneStateListener object in LockScreen, register it with the TelephonyManager service. For LockScreen objects, a LockScreen object is created when the screen lock interface needs to be displayed. When the screen lock interface disappears, the LockScreen object is released.

However, if you forget to cancel the previously registered PhoneStateListener object when releasing the LockScreen object, LockScreen cannot be reclaimed. If the screen lock interface is constantly displayed and disappears, a large number of LockScreen objects cannot be recycled, causing OutOfMemory and causing the system_process process to crash.

Although some system programs can automatically cancel registration (of course not timely), we should explicitly cancel registration in our program, when the program ends, all registration should be canceled.

6. Memory leakage caused by not clearing collection container objects

We usually add some object references to the collection container (such as ArrayList). When we don't need this object, we didn't clear its references from the collection, in this way, the set will become larger and larger. If the set is static, the situation is more serious.

7. Misuse of static keywordsWhen a member variable of a class is declared static, it belongs to the class rather than the object. If we declare a large resource object (such as Bitmap and context) as static, these resources will not be recycled along with the collection of objects and will always exist. Therefore, be cautious when defining member variables using the static keyword. 8. The WebView object is not destroyed.When we do not use a WebView object, we should call its destory () function to destroy it and release its occupied memory. Otherwise, the occupied memory cannot be recycled for a long time, this causes memory leakage. 9. GridView abuseThe implementation of GridView and ListView is not the same. The View of the GridView is not created in real time, but all saved in the memory. For example, a GridView has 100 items. Although we can only see 10 items, the entire 100 items are in the memory.


 




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.