Android--memory leaks

Source: Internet
Author: User

Android allocates different memory usage caps for different types of processes, and if the application process uses more memory than this limit, it is considered a memory leak and is killed by the system. The upper memory limit that Android allocates for the app process is as follows:

Location:/android_source/system/core/rootdir/init.rc section Script

# Define The Oom_adj values forThe classes of processes that can be# killed by the kernel. These is usedinchActivitymanagerservice. SetProp ro. Foreground_app_adj0setprop ro. Visible_app_adj1setprop ro. Secondary_server_adj2setprop ro. Backup_app_adj2setprop ro. Home_app_adj4setprop ro. Hidden_app_min_adj7setprop ro. Content_provider_adj -setprop ro. Empty_app_adj the# Define The memory thresholds atwhichThe above process classes will# be killed. These numbers isinchpages (4k). SetProp ro. Foreground_app_mem1536setprop ro. Visible_app_mem2048setprop ro. Secondary_server_mem4096setprop ro. Backup_app_mem4096setprop ro. Home_app_mem4096setprop ro. Hidden_app_mem5120setprop ro. Content_provider_mem5632setprop ro. Empty_app_mem6144# Write value must is consistent with the above properties.# Note , the driver only supports6slots, so we had Home_app at the# same memory level as services. Write/sys/module/lowmemorykiller/parameters/adj0,1,2,7, -, the     Write/proc/sys/vm/overcommit_memory1    Write/proc/sys/vm/min_free_order_shift4    Write/sys/module/lowmemorykiller/parameters/minfree1536,2048,4096,5120,5632,6144# Set init its forked children's Oom_adj.    Write/proc/1/oom_adj- -

Due to the limited memory available to our applications, there is a need to pay special attention to memory usage issues when writing code. The following are some common cases of improper memory usage.

Query database does not close cursors

The process of querying the database is often done, but there are often cases where the cursor is not closed after it has been used. If our query result set is relatively small, the memory consumption is not easy to find, only in the case of a large number of operations in a constant time to reproduce the memory problem, which will give future testing and troubleshooting difficulties and risks.

Example code:

cursor cursor = getcontentresolver (). Query (Uri ...); if (Cursor.movetonext ()) {    ...}

To fix the 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        }    }}

When constructing adapter, no cached Convertview is used

To construct the baseadapter of the ListView as an example, the method is improved in Baseadapter:

Public View GetView (int position, view Convertview, ViewGroup parent)

To provide the ListView with the View object that each item needs. Initially, the ListView instantiates a certain number of view objects from the Baseadapter based on the current screen layout, and the ListView caches the View objects. When you scroll up the ListView, the View object that was originally on the top list item is recycled and then used to construct the newly-appearing list item. This construction process is done by the GetView () method, and the second parameter view convertview of GetView () is the view object of the cached list item (the cache does not have a view object when it is initialized, and Convertview is null.) )。

It can be seen that if we do not use Convertview, but each time in the GetView () to re-instantiate a view object, that is, wasting resources is also a waste of time, it will also make memory consumption more and more. The process of retrieving the View object of the list item can be viewed by the ListView:

Android.widget.AbsListView.java-to-void Addscrapview (View scrap) method.

Example code:

 Public View GetView (int  position, view Convertview, ViewGroup parent) {    new  Xxx (...);    ... ...     return view;}

To fix the sample code:

 public  View getView (int   position, view Convertview, ViewGroup parent) {View view  = null  ;  if  (Convertview! = null   = Convertview;        Populate (view, GetItem (position)); ...    }  else   {view  = new   Xxx (...);    ...    }  return   view;}  

Bitmap object does not call recycle () to free memory when it is in use

Sometimes we will manipulate the bitmap object manually, if a bitmap object compares memory, when it is not in use, you can call the Bitmap.recycle () method to reclaim the memory occupied by the pixel of this object, but this is not necessary, depending on the situation. You can look at the comments in the code:

 /**   * free up the memory associated with this Bitmap ' s pixels, and mark the * Bitmap as "dead", meaning it would throw an exception if getpixels () or * setPixels () is called, and would draw nothing. This operation cannot is * reversed, so it should is called if you are sure there is no * further uses for T He bitmap.      Normally need * not being called, since the normal GC process would free up this memory when     * There is no more references to this bitmap.  */ 

Releasing a reference to an object

This situation is more cumbersome to describe, with two examples to illustrate.

Example A:

Suppose you have the following actions

 public  class  demoactivity extends   Activity {...  private  Handler mhandler = ...  private      Object obj;  public  void   operation () {obj  = initobj ();     ...            [Mark] Mhandler.post ( new   Runnable () {  public  void   run () {useobj (obj);    }     }); }}

We have a member variable, obj, in operation () we want to be able to post the operation that handles the obj instance to the MessageQueue of a thread. In the above code, even if the thread mhandler is using the object referenced by obj, the object will not be garbage collected because Demoactivity.obj still retains a reference to the object. So if you no longer use this object in Demoactivity, you can release the object's reference at [Mark], and the code can be modified to:

... ...  Public void operation () {    = initobj ();    ...     Final Object o = obj;     NULL ;    Mhandler.post (new  Runnable () {        publicvoid  run () {            useobj (o);}}    ... ...

Example B:

Suppose we want to listen to the phone service in the system in the lock screen (lockscreen) to get some information (such as signal strength, etc.), you can define a Phonestatelistener object in the Lockscreen. Register it with the Telephonymanager service at the same time. For Lockscreen objects, a Lockscreen object is created when the lock screen needs to be displayed, and the Lockscreen object is released when the lock screen disappears.

However, if you forget to cancel the Phonestatelistener object that we previously registered when releasing the Lockscreen object, it will cause lockscreen to be garbage collected. If the lock screen interface is constantly displayed and disappears, it will eventually cause outofmemory due to the fact that a large number of Lockscreen objects have no way to be recycled, causing the system_process process to hang out.

In short, when an object A with a shorter life cycle has its reference by a long-life object B, at the end of A's life cycle, a reference to A is cleared in B.

Other

The most typical use of Android applications is to be aware of the need to release resources in the life cycle of the activity, in the OnPause (), OnStop (), OnDestroy () methods, in the case of the appropriate release of resources.

I'm the dividing line of the king of the Land Tiger.

Reference: http://rayleeya.iteye.com/blog/727074

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.