标签: android 管理 应用 | 发表时间:2015-07-21 19:43 | 作者:leelit


only way to completely release memory from your app is to release object references you may be holding, making the memory available to the garbage collector.

How Android Manages Memory


1、Sharing Memory

In order to fit everything it needs in RAM, Android tries to share RAM pages across processes. It can do so in the following ways:

1)Each app process is forked from an existing process called Zygote.
2)Most static data is mmapped into a process.
3)In many places, Android shares the same dynamic RAM across processes using explicitly allocated shared memory regions (either with ashmem or gralloc).

2、Allocating and Reclaiming App Memory

Here are some facts about how Android allocates then reclaims memory from your app:

1)The Dalvik heap for each process is constrained to a single virtual memory range.
每个进程的Dalvik heap被限定在一个内存区间。
2)The logical size of the heap is not the same as the amount of physical memory used by the heap.
3)The Dalvik heap does not compact the logical size of the heap, meaning that Android does not defragment the heap to close up space. Android can only shrink the logical heap size when there is unused space at the end of the heap.
Dalvik heap不会为了使内存连续而整理内存碎片

3、Restricting App Memory


To maintain a functional multi-tasking environment, Android sets a hard limit on the heap size for each app. The exact heap size limit varies between devices based on how much RAM the device has available overall. If your app has reached the heap capacity and tries to allocate more memory, it will receive an OutOfMemoryError.

4、Switching Apps


Instead of using swap space when the user switches between apps, Android keeps processes that are not hosting a foreground (“user visible”) app component in a least-recently used (LRU) cache. For example, when the user first launches an app, a process is created for it, but when the user leaves the app, that process does not quit. The system keeps the process cached, so if the user later returns to the app, the process is reused for faster app switching.

How Your App Should Manage Memory


You should apply the following techniques while designing and implementing your app to make it more memory efficient.

1、Use services sparingly


1)If your app needs a service to perform work in the background, do not keep it running unless it’s actively performing a job. Also be careful to never leak your service by failing to stop it when its work is done.
2)When you start a service, the system prefers to always keep the process for that service running. This makes the process very expensive because the RAM used by the service can’t be used by anything else or paged out.
3)The best way to limit the lifespan of your service is to use an IntentService, which finishes itself as soon as it’s done handling the intent that started it.

2、Release memory when your user interface becomes hidden


1) When the user navigates to a different app and your UI is no longer visible, you should release any resources that are used by only your UI.
2)To be notified when the user exits your UI, implement the onTrimMemory() callback in your Activity classes. You should use this method to listen for the TRIM_MEMORY_UI_HIDDEN level, which indicates your UI is now hidden from view and you should free resources that only your UI uses.
3)So although you should implement onStop() to release activity resources such as a network connection or to unregister broadcast receivers, you usually should not release your UI resources until you receive onTrimMemory(TRIM_MEMORY_UI_HIDDEN). This ensures that if the user navigates back from another activity in your app, your UI resources are still available to resume the activity quickly.

3、Release memory as memory becomes tight


During any stage of your app’s lifecycle, the onTrimMemory() callback also tells you when the overall device memory is getting low. You should respond by further releasing resources based on the following memory levels delivered by onTrimMemory():
在应用的所有生命周期中,onTrimMemory() 回调可以告诉你设备内存是不是下降着,你应该根据以下反应不同程度内存使用状况的系统回调作出相应的资源释放操作。


Also, when your app process is currently cached, you may receive one of the following levels from onTrimMemory():


When the system begins killing processes in the LRU cache, although it primarily works bottom-up, it does give some consideration to which processes are consuming more memory and will thus provide the system more memory gain if killed

4、Check how much memory you should use


As mentioned earlier, each Android-powered device has a different amount of RAM available to the system and thus provides a different heap limit for each app. You can call getMemoryClass() to get an estimate of your app’s available heap in megabytes. If your app tries to allocate more memory than is available here, it will receive an OutOfMemoryError.

In very special situations, you can request a larger heap size by setting the largeHeap attribute to “true” in the manifest tag. If you do so, you can call getLargeMemoryClass() to get an estimate of the large heap size.
特殊情况下,你可以通过在manifest文件 节点下设置largeHeap属性为true申请更大的堆内存,如果你这样做,可以调用getLargeMemoryClass()来查看可分配到的更大的堆内存。

Additionally, the large heap size is not the same on all devices and, when running on devices that have limited RAM, the large heap size may be exactly the same as the regular heap size.

5、Avoid wasting memory with bitmaps


6、Use optimized data containers


Take advantage of optimized containers in the Android framework, such as SparseArray, SparseBooleanArray, and LongSparseArray.
使用Android API中的优化容器,如SparseArray、SparseBooleanArray,、LongSparseArray等来替代HaspMap等容器。

7、Be aware of memory overhead


1)Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
2)Every class in Java (including anonymous inner classes) uses about 500 bytes of code.
3)Every class instance has 12-16 bytes of RAM overhead.
4)Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

8、Be careful with code abstractions


9、Use nano protobufs for serialized data

序列化数据时使用nano protobufs

10、Avoid dependency injection frameworks


these frameworks tend to perform a lot of process initialization by scanning your code for annotations, which can require significant amounts of your code to be mapped into RAM even though you don’t need it.

11、Be careful about using external libraries


12、Optimize overall performance

优化整体表现,这在training doc中有一个专门章节。

13、Use ProGuard to strip out any unneeded code


The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names.Using ProGuard can make your code more compact, requiring fewer RAM pages to be mapped.

14、Use zipalign on your final APK


If you do any post-processing of an APK generated by a build system (including signing it with your final production certificate), then you must run zipalign on it to have it re-aligned. Failing to do so can cause your app to require significantly more RAM, because things like resources can no longer be mmapped from the APK.

15、Analyze your RAM usage


Once you achieve a relatively stable build, begin analyzing how much RAM your app is using throughout all stages of its lifecycle. For information about how to analyze your app, read Investigating Your RAM Usage.
详细信息,看Investigating Your RAM Usage 这一章节。里面不仅会介绍常用的MAT,还有一些其他技巧。

16、Use multiple processes


If it’s appropriate for your app, an advanced technique that may help you manage your app’s memory is dividing components of your app into multiple processes.This technique must always be used carefully and most apps should not run multiple processes, as it can easily increase—rather than decrease—your RAM footprint if done incorrectly. It is primarily useful to apps that may run significant work in the background as well as the foreground and can manage those
operations separately.

You can specify a separate process for each app component by declaring the android:process attribute for each component in the manifest file.


作者:leelit 发表于2015/7/21 11:43:28 原文链接
阅读:57 评论:0 查看评论

相关 [android 管理 应用] 推荐:


- - CSDN博客推荐文章
所有内容均来源于官方文档 only way to completely release memory from your app is to release object references you may be holding, making the memory available to the garbage collector.


- - CSDN博客推荐文章
首先Android内存管理机制相当复杂,想要讲清楚比较困难;其次对于绝大多数用户来说,只关心内存够不够用,至于内存如何管理的这种技术细节,不是用户需要去考虑的,写这样一个专题有没有意义. 毕竟我们是用手机,不是来研究手机的. 最后的顾虑是这个专题会不会太技术化了,绝大部分用户不会看或者说缺乏相应的背景.

应用助手for Android发布更新:支持SD卡文件管理

- 洞箫 - cnBeta.COM
8月23日新上线的应用助手for Android今日发布更新,新增SD卡文件管理,全面升级截图功能,还可以DIY手机截图动态图片,让我们能轻松便捷通过PC管理Android手机资源下载热门应用,大家快来体验给力的新版本:.

GetEd2k (Android应用)

- 某牢 - eMule Fans 电骡爱好者
GetEd2k是一个Android应用程序,作者是anacletus. 此应用可以帮助你把网页中的电驴(eDonkey) 链接添加到你个人电脑的电驴客户端里,不过前提是你的客户端开启了用于远程控制的Web interface(Web服务器,网页接口,Web界面),当然,eMule(电骡), MLDonkey 和 aMule 都支持该功能,所以这三种主流电驴客户端的用户都可以使用GetEd2k.


- - CSDN博客移动开发推荐文章
相信一步步走过来的Android从业者,每个人都会遇到OOM的情况. 如何避免和防范OOM的出现,对于每一个程序员来说确实是一门必不可少的能力. 今天我们就谈谈在Android平台下内存的管理之道,开始今天的主题之前,先再次回顾两个概念. 内存泄漏:对象在内存heap堆中中分配的空间,当不再使用或没有引用指向的情况下,仍不能被GC正常回收的情况.

Android 应用程序

- - CSDN博客推荐文章
Android 应用程序由四个模块构造而成:Activity、Intent 、Content Provider 、Service. 下面简单介绍一下如下模块的含义:. 1、Activity  "活动". 一个Activity就是单独的屏幕,每一个活动都被实现为一个独立的类,并且从活动基类中继承而来,活动类将会显示由视图控件组成的用户接口并对事件作出响应.


- - CSDN博客移动开发推荐文章
原文地址: android应用程序一旦装进设备,每个程序会在它自己安全的沙盒里运行. 1.android操作系统是一个多用户linux系统,每一个应用程序是一个用户. 2.默认情况下,系统会为每个app分配唯一的linux用户id(这个id只会被系统使用,并且只会被这个app知道),系统为每个app的所有文件都设置了权限,只有被分配了这个app用户ID的程序可以访问它.


- iBeyond - Tech2IPO
相信很多使用Android手机用户都会有相同的烦恼:手机电池耗费太快,常常撑不过一天,上班不得不带跟USB线充电,一出门就担心电力不足……实际上,如果你连着Wifi或者3G网络,所有的桌面Widget,后台更新的程序,短信电话等等会让你的手机根本撑不过一个白天. 当然,你可以在电力紧缺的时候手动关闭3G、流量、GPS、杀掉所有程序……但不是每个人都有时间手动去做这些设置.


- Niclau - Solidot
Helen Swann 写道 "文件管理器是管理文件的软件,帮助用户处理日常工作,管理储存在本地和网络中的文件. 所有文件管理器都提供了基本的操作如创建、打开、查看、编辑、移动和删除文件. 许多Android文件管理器还提供了额外功能,如网络连接、应用程序管理、存档和压缩处理、搜索等. 这篇文章介绍了 10款Android文件管理器,供感兴趣的用户参考.


- - 移动开发 - ITeye博客
上一篇文章总结了一下内存分析的方法,这次聊聊如何出现解决和避免内存相关的问题.  你的应用到底有多少的heapsize可以通过:  . 来获取(注意,这里的单位是K). 我测试了几个手机,Galaxy nexus 可以申请到256M的heapsize,256M啊,同学们,这是多么的奢侈啊,但是人家谷歌说的很清楚,用这个标签一定要慎重,除非你是真的需要这么多内存,不能把这玩意作为快速解决OOM的手段,如果你的内存使用过多,还是先慎重的分析一下你的内存到哪里去了,因为这会导致GC的时间较长并且会影响系统的性能,原文如下:.