An explanation of the various reasons for Android memory leaks

Source: Internet
Author: User

Ext.: http://mobile.51cto.com/abased-406286.htm

1. Memory leaks due to resource object not shutting down

Describe:

Resource objects such as (cursor,file files, etc.) often use some buffering, we should close them in time when we are not in use, so that their buffers can recover memory in time. Their buffering exists not only in the Java Virtual machine, but also outside the Java Virtual machine. If we simply set its reference to null without shutting them down, it often causes a memory leak. Because some resource objects, such as Sqlitecursor (in the destructor Finalize (), if we do not close it, it itself will close () closed), if we do not close it, the system will be recycled it also closed it, but this is too low efficiency. Therefore, when the resource object is not in use, it should call its close () function, close it, and then set it to null. Be sure that our resource objects are closed when our program exits.

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:

    1. cursor cursor = getcontentresolver (). Query (URI ...);
    2. if (Cursor.movetonext ()) {
    3. ... ...
    4. }

To fix the sample code:

  1. cursor cursor = null;
  2. try {
  3. cursor = Getcontentresolver (). Query (URI ...);
  4. if (cursor! = null &&cursor.movetonext ()) {
  5. ... ...
  6. }
  7. } finally {
  8. if (cursor! = null) {
  9. try {
  10. Cursor.close ();
  11. } catch (Exception e) {
  12. Ignore this
  13. }
  14. }
  15. }

2. When constructing adapter, no cached Convertview is used

Describe:

To construct the baseadapter of a ListView, for example, a method is provided in Baseadapter:

Public View GetView (int position, Viewconvertview, 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--Voidaddscrapview (View scrap) method.

Example code:

    1. Public View GetView (int position, Viewconvertview, ViewGroup parent) {
    2. View view = new Xxx (...);
    3. ... ...
    4. return view;
    5. }

To fix the sample code:

  1. Public View GetView (int position, Viewconvertview, ViewGroup parent) {
  2. View view = null;
  3. if (convertview! = null) {
  4. view = Convertview;
  5. Populate (view, GetItem (position));
  6. ...
  7. } Else {
  8. View = new Xxx (...);
  9. ...
  10. }
  11. return view;
  12. }

3.Bitmap object is not in use call recycle () to free memory

Describe:

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:

  1. /**
  2. free up the memory associated with Thisbitmap ' s pixels, and mark the
  3. bitmap as "dead", meaning Itwill throw an exception if getpixels () or
  4. setpixels () is called, and would drawnothing. This operation cannot is
  5. reversed, so it should is called ifyou is sure there is no
  6. further uses for the bitmap. This is anadvanced call, and normally need
  7. not be called, since the normal gcprocess would free up this memory when
  8. There is no more references to Thisbitmap.
  9. */

4. Try to use the context of application to replace the context associated with activity

This is a very cryptic case of a memory leak. There is an easy way to avoid context-related memory leaks. The most notable one is to avoid the context escaping from his own range. Use Application context. The life cycle of this context is as long as your application's life cycle, not the activity's life cycle. If you want to keep a long-lived object, and this object needs a context, remember to use the Application object. You can get it by calling Context.getapplicationcontext () or activity.getapplication (). More please see how this article avoids

Android memory leaks.

5. Memory leaks due to registration not canceled

Some Android programs may refer to the objects of our Anroid program (such as the registration mechanism). Even though our Android program is over, other reference programs still have a reference to an object in our Android program, and the leaked memory is still not garbage collected. Unregisterreceiver was not called after calling Registerreceiver.

For example, suppose we want to listen to the telephony 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.

Although some system programs, it seems that it can be automatically unregistered (of course, not in time), but we should still clear in our program to unregister, the end of the program should be all the registration is canceled.

6. Memory leaks caused by objects not cleaned up 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. If the set is static, the situation is even worse.

An explanation of the various reasons for Android memory leaks

Related Article

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.