Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release memory in android to avoid memory leak

While going through the android developer site i found this it says to avoid memory leak we should release resources  in onStop().

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

like image 677
Shakeeb Ayaz Avatar asked Jul 27 '13 06:07

Shakeeb Ayaz


People also ask

How is the memory release in Android?

The only way to release memory from an app is to release object references that the app holds, making the memory available to the garbage collector. That is with one exception: any files mmapped in without modification, such as code, can be paged out of RAM if the system wants to use that memory elsewhere.

How do you prevent memory leaks?

To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.

What can cause memory leak in Android?

Memory leaks occur when an application allocates memory for an object, but then fails to release the memory when the object is no longer being used. Over time, leaked memory accumulates and results in poor app performance and even crashes.


1 Answers

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
like image 82
Kai Avatar answered Sep 21 '22 02:09

Kai