How to release memory in android to avoid memory l

2019-04-06 05:23发布

问题:

While going through the android developer site i found this .

it says to avoid memory leak we should release resources in onStop()but how to do so.

回答1:

Basically any objects that are properly nulled are considered released and their memory can be reclaimed by the OS. Your question is too general and it's hard to offer a exhaustive list of methods, but you should generally be aware of these:

  1. Stop/close any services/files/connections that you no longer need
  2. Do NOT store any Drawable in any static Object, Drawables hold references to their owner View's which hold references to their owner Activity's, so if you hold on to any Drawable you will hold onto a lot of objects/memory unnecessarily
  3. For an utility app, you probably needn't worry about memory; but for apps that use lots of Bitmaps, you should have a deep understanding of Bitmap management and how Bitmaps are used in your app in order to manage them effectively


回答2:

There are a few notorious examples of memory hogs, with media (audio/video) and large bitmaps being the biggest memory hogs. Most things are taken care of by removing all pointers to them and letting GC have its way with them. Bitmaps, however, can be recycled more immediately by using:

if (yourBitmap != null) {
    yourBitmap.recycle();
    youBitmap = null;
}

Your media should be stopped and de-referenced. But it should be stopped in onPause(), and not left until onStop().