简体   繁体   中英

How to release memory in Android?

我想知道如何以编程方式在Android中释放内存,因为我的布局包含很多视图,并且当我转到任何“活动”时,应用程序都会停止工作,并给我显示内存不足错误。

So what is the way to release Memory  ?

Android Already define How to use that Click here.

Possible Reasons:

There are number of reasons why we get a Out of memory errors. Some of those are:

  1. You are doing some operation that continuously demands a lot of memory and at some point it goes beyond the max heap memory limit of a process.

  2. You are leaking some memory ie you didn't make the previous objects you allocated eligible for Garbage Collection (GC). This is called Memory leak.

  3. You are dealing with large bitmaps and loading all of them at run time. You have to deal very carefully with large bitmaps by loading the size that you need not the whole bitmap at once and then do scaling.

Tools to Diagnose OOM :

In Android there are some tools that can be used to find the memory leaks and one of them is MAT (Memory Analyzer Tool). This can be used as a plugin to Eclipse or as a stand alone tool.

Lets start with installing MAT and using it with Eclipse with a step by step guide:

  1. To start up with this tool you have to download this tool from link :
  2. Start Eclipse and run your application.
  3. Go to DDMS and select your application and click the Dump HPROF file button and it will ask you to save the hprof file. Save it on your hard disk.
  4. Run the MemoryAnalyzer.exe file situated in the MAT package downloaded.
  5. his MAT tool will not understand the hprof file generated by Eclipse so you have to convert it using the hprof-conv tool in the tools folder of android-sdk using the following command:

hprof-conv com.example.android.hcgallery.hprof mat.hprof

  • Now this file is ready to use with MAT.

在此处输入图片说明

And one more things i found that Memory Analysis for Android Applications

You cant just release memory it is the garbage collectors jobs to find the reference of this object if the object is not used then garbage collector kicks in.

The problem is that you have a lots of nested View which consumes a lot of memory, you can either minimized your views to use less memory space in the heap or dynamically add the view when you need it and remove other views when you dont need it to save memory space.

I use this onBackPressed event, and it totally release my app process:

android.os.Process.killProcess(android.os.Process.myPid());

Hope it help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM