Android进程的内存管理分析

首先,回顾一下基础知识,基础知识是理解系统机制的前提和关键:

1、  进程的地址空间

在32位操作系统中,进程的地址空间为0到4GB,

示意图如下:

20130513154042627

这里主要说明一下Stack和Heap:

Stack空间(进栈和出栈)由操作系统控制,其中主要存储函数地址、函数参数、局部变量等等,所以Stack空间不需要很大,一般为几MB大小。

Heap空间的使用由程序员控制,程序员可以使用malloc、new、free、delete等函数调用来操作这片地址空间。Heap为程序完成各种复杂任务提供内存空间,所以空间比较大,一般为几百MB到几GB。正是因为Heap空间由程序员管理,所以容易出现使用不当导致严重问题。

2、进程内存空间和RAM之间的关系

进程的内存空间只是虚拟内存(或者叫作逻辑内存),而程序的运行需要的是实实在在的内存,即物理内存(RAM)。在必要时,操作系统会将程序运行中申请的内存(虚拟内存)映射到RAM,让进程能够使用物理内存。

RAM作为进程运行不可或缺的资源,对系统性能和稳定性有着决定性影响。另外,RAM的一部分被操作系统留作他用,比如显存等等,内存映射和显存等都是由操作系统控制,我们也不必过多地关注它,进程所操作的空间都是虚拟地址空间,无法直接操作RAM。

示意图如下:

20130513154359212

3、  Android中的进程

(1)   native进程:采用C/C++实现,不包含dalvik实例的进程,/system/bin/目录下面的程序文件运行后都是以native进程形式存在的。如下图所示,/system/bin/surfaceflinger、/system/bin/rild、procrank等就是native进程。

(2)   java进程:Android中运行于dalvik虚拟机之上的进程。dalvik虚拟机的宿主进程由fork()系统调用创建,所以每一个java进程都是存在于一个native进程中,因此,java进程的内存分配比native进程复杂,因为进程中存在一个虚拟机实例。如下图,Android系统中的应用程序基本都是java进程,如桌面、电话、联系人、状态栏等等。

20130513155151825

4、  Android中进程的堆内存

进程空间中的heap空间是我们需要重点关注的。heap空间完全由程序员控制,我们使用的malloc、C++ new和java new所申请的空间都是heap空间, C/C++申请的内存空间在native heap中,而java申请的内存空间则在dalvik heap中。

20130513155252901

5、  Android的 java程序为什么容易出现OOM

这个是因为Android系统对dalvik的vm heapsize作了硬性限制,当java进程申请的java空间超过阈值时,就会抛出OOM异常(这个阈值可以是48M、24M、16M等,视机型而定),可以通过adb shell getprop | grep dalvik.vm.heapgrowthlimit查看此值。

也就是说,程序发生OMM并不表示RAM不足,而是因为程序申请的java heap对象超过了dalvik vm heapgrowthlimit。也就是说,在RAM充足的情况下,也可能发生OOM。

这样的设计似乎有些不合理,但是Google为什么这样做呢?这样设计的目的是为了让Android系统能同时让比较多的进程常驻内存,这样程序启动时就不用每次都重新加载到内存,能够给用户更快的响应。迫使每个应用程序使用较小的内存,移动设备非常有限的RAM就能使比较多的app常驻其中。但是有一些大型应用程序是无法忍受vm heapgrowthlimit的限制的,后面会介绍如何让自己的程序跳出vm heapgrowthlimit的限制。

6、  Android如何应对RAM不足

在第5点中提到:java程序发生OMM并不是表示RAM不足,如果RAM真的不足,会发生什么呢?这时Android的memory killer会起作用,当RAM所剩不多时,memory killer会杀死一些优先级比较低的进程来释放物理内存,让高优先级程序得到更多的内存。我们在分析log时,看到的进程被杀的log,如图5,往往就是属于这种情况。

20130513155457553

7、  如何查看RAM使用情况

可以使用

查看RAM使用情况:

这里对其中的一些字段进行解释:

MemTotal:可以使用的RAM总和(小于实际RAM,操作系统预留了一部分)

MemFree:未使用的RAM

Cached:缓存(这个也是app可以申请到的内存)

HightTotal:RAM中地址高于860M的物理内存总和,只能被用户空间的程序使用。

HightFree:RAM中地址高于860M的未使用内存

LowTotal:RAM中内核和用户空间程序都可以使用的内存总和(对于512M的RAM: lowTotal= MemTotal)

LowFree: RAM中内核和用户空间程序未使用的内存(对于512M的RAM: lowFree = MemFree)

8、  如何查看进程的内存信息

(1)、使用

从下图可以看出,com.example.demo作为java进程有2个heap,native heap和dalvik heap,native heap size为159508KB,dalvik heap size为46147KB

20130513155636097

(2)使用

查看进程内存信息

20130513155739454

解释一些字段的意思:

VSS- Virtual Set Size 虚拟耗用内存(包含共享库占用的内存)

RSS- Resident Set Size 实际使用物理内存(包含共享库占用的内存)

PSS- Proportional Set Size 实际使用的物理内存(比例分配共享库占用的内存)

USS- Unique Set Size 进程独自占用的物理内存(不包含共享库占用的内存)

一般来说内存占用大小有如下规律:VSS >= RSS >= PSS >= USS

注意:procrank可以查看native进程和java进程,而dumpsys meminfo只能查看java进程。

9、  应用程序如何绕过dalvikvm heapsize的限制

对于一些大型的应用程序(比如游戏),内存使用会比较多,很容易超超出vm heapsize的限制,这时怎么保证程序不会因为OOM而崩溃呢?

(1)创建子进程

创建一个新的进程,那么我们就可以把一些对象分配到新进程的heap上了,从而达到一个应用程序使用更多的内存的目的,当然,创建子进程会增加系统开销,而且并不是所有应用程序都适合这样做,视需求而定。

创建子进程的方法:使用android:process标签

(2)使用jni在native heap上申请空间(推荐使用)

nativeheap的增长并不受dalvik vm heapsize的限制,从图6可以看出这一点,它的native heap size已经远远超过了dalvik heap size的限制。

只要RAM有剩余空间,程序员可以一直在native heap上申请空间,当然如果 RAM快耗尽,memory killer会杀进程释放RAM。大家使用一些软件时,有时候会闪退,就可能是软件在native层申请了比较多的内存导致的。比如,我就碰到过UC web在浏览内容比较多的网页时闪退,原因就是其native heap增长到比较大的值,占用了大量的RAM,被memory killer杀掉了。

(3)使用显存(操作系统预留RAM的一部分作为显存)

使用OpenGL textures等API,texture memory不受dalvik vm heapsize限制,这个我没有实践过。再比如Android中的GraphicBufferAllocator申请的内存就是显存。

10、Bitmap分配在native heap还是dalvik heap上?

答案是 Android 2.X 版本上,大部分都是在 native heap上面,dalvik heap上保存引用,因此才会在Android 文档上明确推荐手动调用 recycle 函数回收内存。从3.X版本开始,都在dalvik heap上开辟内存,因此也就没有上述的推荐调用了。

摘自 http://blog.csdn.net/gemmem/article/details/8920039

Android + Eclipse: No grammar constraints (DTD or XML schema) detected for the document.

I don’t like having warnings in the code, and recently I’ve been getting a lot of these, these seem to popup after you accidentally press the Validate button in Eclipse…

Anyway, it is a easy fix, set the Validator to ignore (See screenshot below). Once you have changed the setting, you may have to Validate the files again (right click file -> Validate)dtd
原文 http://ucla.jamesyxu.com/?p=148

Android 4.2.2 API 17 Content Provider 报错 SecurityException: Permission Denial: opening provider

两个APK 通过Content Provider 来共享数据,在Android 4.2.2 API 17  之前都是正常的,但是到Android 4.2.2 API 17  上面就会报告异常类似如下的异常信息

在AndroidManifest.xml中原来的定义如下

并且没有定义 android:targetSdkVersion

查找了很多地方,最终发现原因

具体的网页在 http://developer.android.com/about/versions/android-4.2.html

因此修改为如下即可 也就是增加 android:exported="true"

VelocityTracker简单用法

VelocityTracker顾名思义即速度跟踪,在android中主要应用于touch event, VelocityTracker通过跟踪一连串事件实时计算出

当前的速度,这样的用法在android系统空间中随处可见,比如Gestures中的Fling, Scrolling等,下面简单介绍一下用法。

下面是我写的一个简单Demo:

代码很简单,我们可以求出move过程中的伪瞬时速度, 这样在做很多控件的时候都是可以用到的,比如系统Launcher的分页,

ScrollView滑动等, 可根据此时的速度来计算ACTION_UP后的减速运动等。实现一些非常棒的效果。

原始链接 http://blog.csdn.net/bingxianwu/article/details/7446799

Mac OS X 10.9 使用 Hardware Accelerated Execution 之后死机问题

为了加速电脑上面的Android  模拟器,可以使用Intel Atom 模拟器,但是在升级到10.9 之后发生死机问题,开启到一半,电脑整个卡住。搜索了一下,需要到intel 下载针对 10.9 的补丁版本

下载地址为

http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager/

屏幕快照 2013-11-27 上午11.58.54注意 下载 Hotfix for OS X 10.9 only

Proguard代码混淆/反混淆简介

  • proguard 原理

Java代码编译成二进制class 文件,这个class 文件也可以反编译成源代码 ,除了注释外,原来的code 基本都可以看到。为了防止重要code 被泄露,我们往往需要混淆(Obfuscation code , 也就是把方法,字段,包和类这些java 元素的名称改成无意义的名称,这样代码结构没有变化,还可以运行,但是想弄懂代码的架构却很难。 proguard 就是这样的混淆工具,它可以分析一组class 的结构,根据用户的配置,然后把这些class 文件的可以混淆 java 元素名混淆掉。在分析class 的同时,他还有其他两个功能,删除无效代码(Shrinking 收缩),和代码进行优化 (Optimization Options)。
缺省情况下,proguard 会混淆所有代码,但是下面几种情况是不能改变java 元素的名称,否则就会这样就会导致程序出错。
一, 我们用到反射的地方。
二, 我们代码依赖于系统的接口,比如被系统代码调用的回调方法,这种情况最复杂。
三, 是我们的 java 元素名称是在配置文件中配置好的。
所以使用proguard时,我们需要有个配置文件告诉 proguard 那些 java 元素是不能混淆的。

继续阅读Proguard代码混淆/反混淆简介

Android Support v4、v7、v13的区别和应用场景

google提供了Android Support Library package 系列的包来保证来高版本sdk开发的向下兼容性,即我们用4.x开发时,在1.6等版本上,可以使用高版本的有些特性,如fragement,ViewPager等,下面,简单说明下这几个版本间的区别:

Android Support v4 这个包是为了照顾1.6及更高版本而设计的,这个包是使用最广泛的,eclipse新建工程时,都默认带有了。

    Android Support v7:  这个包是为了考虑照顾2.1及以上版本而设计的,但不包含更低,故如果不考虑1.6,我们可以采用再加上这个包,另外注意,v7是要依赖v4这个包的,即,两个得同时被包含。

    Android Support v13  :这个包的设计是为了android 3.2及更高版本的,一般我们都不常用,平板开发中能用到。

Why your Android NDK breakpoints might fail and how to fix them

Overview

 

First of all let's overview the structure of a typical Android app containing native code:

native1

The app code is stored inside an .apk file that is essentially a ZIP archive containing the classes.dex file (with all the Java code) and one or more native libraries in lib\<EABI name> subdirectory. The typical lifecycle of an application with native code is the following:

  1. The Android OS loads the Java code and starts executing it
  2. The Java code calls System.loadLibrary() to load a native library.
  3. The Java code starts calling functions from the native code.

Each native library exists in 2 versions:

  •  A "full" version debugging information that associates code addresses inside the library with source files and lines. This version resides in obj\local\armeabi under your project directory.
  • A "stripped" version without the debugging information that resides in libs\armeabi and gets packaged into the APK file.

While the Android device runs the smaller "stripped" version of the library, the GDB debugger needs the larger "non-stripped" version to map source files into addresses and vice versa:

native2

Setting breakpoints

 

When you set a breakpoint on a given line of a source file, the GDB debugger needs to perform certain computations before the breakpoint can be physically created and starts triggering. Assume libNative1 is loaded at address 0x10000 and the user is setting a breakpoint in line 24 of c:\main.cpp. GDB will do the following before it can set a breakpoint:

  1. GDB starts searching all loaded libraries for the file called "c:\main.cpp". In this example the Android OS only reports the libNative1.so library.
  2. GDB looks inside obj\local\armeabi for a file called libNative1.so which is the "non-stripped" version of the library containing the debug information. GDB reads the symbol table from it and finds c:\main.cpp inside it.
  3. Based on the symbol table GDB computes that line 24 corresponds to offset +0x2. It adds 0x2 to the load address of libNative1.so (0x10000) and sets the breakpoint at 0x10002.

If any of the 3 steps fail, the breakpoint will not be created, or will be created wrongly and will never be hit. The next section explains how to diagnose and fix the related problems.

Diagnosing the problems

This section provides detailed instructions how to check for the most common problems with breakpoints caused by non-standard configurations or missing files:

A. Ensure that the library is loaded

First thing to do is to determine if the native library has been actually loaded and if GDB knows about it. It is done by running the "info shared" command in GDB:

native-sharedlib

The output from the info shared command should include 3 important lines:

  1. Loaded symbols for "linker"
  2. Loaded symbols for "libc.so"
  3. Loaded symbols for all native libraries you want to debug.

Here's an example of those lines:

If some of the libraries are not present, you can force GDB to manually reload the symbols by running the following command in GDB:


If your .so library (e.g. libMyAndroidApp.so) is listed, but the symbols are not loaded ("Syms read" states "no"), GDB was not able to find a non-stripped version of the library. To fix it please run the "show solib-search-path" command in GDB:

native-solib

The obj/local/armeabi directory of your project should be present among the reported directories and it should contain the .so file with symbols. If not, copy the correct .so file into a directory listed here and rerun the "sharedlibrary" command.

You can alternatively force GDB to search additional directories for the .so file using the set solib-search-path command.

If your .so library is not present in the list, it has not been loaded by the Java code yet. Please ensure that System.loadLibrary() is called from your Java code and that it succeeds without any Java exceptions.

B. Ensure that you are using correct file paths

A common cause of many breakpoint problems is a configuration when the directories using for building and debugging your project are different. E.g. if the library was compiled from c:\projects and then the sources were moved to d:\projects, setting a breakpoint in d:\projects\main.cpp will fail, as GDB will not accept c:\projects\main.cpp as a substitute.

Those problems can be diagnosed by looking into the source file lists and comparing them with the file used to set a breakpoint. First of all, remove your breakpoint, try setting your breakpoint again and watch what GDB command is issued by your IDE:

native-break-insert

The -break-insert command used to set a breakpoint will specify a path to your source file.

Run the "info sources" command to see the source files discovered by GDB:

native-info-sources

Copy the output of the command to the clipboard (Ctrl-A, Ctrl-C), paste it into a text editor and search for the source file you are trying to debug (e.g. MyAndroidApp.c):

native-source-list

If the file is not present in the list, you have loaded a wrong version of the .so file (see previous section). If the file is present, but the path is different from the one used in -break-insert command, you have found the cause of your problem. Rebuild your app using the new path, or move the file back to an old location so that the path used for creating breakpoints matches the path reported by the "info sources" command.

Note that GDB requires the file path to be EXACTLY the same as reported by "info sources", including double slash before "jni".

C. Recheck file versions and do a clean build

If your breakpoints are set, but never hit, there is probably a mismatch between the .so file version loaded into the Android application and the .so file version used by GDB to compute addresses from source lines. The most common cause for it is the bug in the Android loader that loads the armeabi library instead of the armeabi-v7a version. If you suspect this to happen, change your build configuration to build either armeabi, or armeabi-v7a platform, but not both at the same time and rebuild your application.'

引用自  http://www.codeproject.com/Articles/493043/Why-your-Android-NDK-breakpoints-might-fail-and-ho

android之StrictMode介绍

Android 2.3起,新增加了一个新的类,叫StrictMode(android.os.StrictMode)。这个类可以用来帮助开发者改进他们编写的应用,并且提供了各种的策略,这些策略能随时检查报告开发者开发应用中存在的问题,比如可以监视那些本不应该在主线程中完成的工作或者其他的一些不规范和不好的代码。

StrictMode的策略和规则

  目前,有两大类的策略可供使用

一类是关于常用的监控方面的

Disk Reads 磁盘读

Disk Writes 磁盘写

Network access 网络访问

Custom Slow Code 自定义的运行速度慢的代码分析

前面三种的意思读者应该很清楚,就是正如它们的名字所示,分别对磁盘的读和写,网络访问进行监控。而第四种的自定义慢代码分析,是仅当访问调用类的时后才触发的,可以通过这种

方法去监视运行缓慢的代码。当在主线程中调用时,这些验证规则就会起作用去检查你的代码。比如,当你的应用在下载或者解析大量的数据时,你可以触发自定义运行速度慢代码的查询分、

析,作用很大。StrictMode可以用于捕捉发生在应用程序主线程中耗时的磁盘、网络访问或函数调用,可以帮助开发者使其改进程序,使主线程处理UI和动画在磁盘读写和网络操作时变得更平

滑,避免主线程被阻塞的发生。

另一类是关于VM虚拟机等方面的策略

内存泄露的Activity对象

内存泄露的SQLite对象

内存泄露的释放的对象

其中,内存泄露的Activity对象和内存泄露的SQLite对象都比较好理解,而所谓对关闭对象的检查,主要是去监那些本该释放的对象,比如应该调用close()方法的对象

相关的违反情况可以记录在LogCat中或者存储在DropBox中(android.os.DropBox)服务中

  如何使用:

  放在activity的周期onCreate方法中

 

Android 源代码 error: Exited sync due to fetch errors…

希望各位不要出现这个错误,出现这个错误就要折腾一会了

首先继续repo sync,若是一直提示这个错误,那么就按照下面的方法来做吧:

关于这个问题其实google是有说明的http://source.android.com/source/downloading.html,为了防止连接数过多,每个ip都需要认证。。。

第一步:从这里 the password generator 获取用户名和密码,前提是你在之前填写了你的真实姓名和邮箱

第二步:将上面的页面上以machine开头的两行复制到 ~/.netrc文件中

第三步:

多了个“/a”,并且指定 “--config-name”

参数,很多时候会用以前配置过的用户名密码,指定这个参数会重新设置用户名

然后就可以repo sync了

特别注意.netrc文件是在用户的根目录下,root用户就是/目录下,如果没有的话就自己建一个,把权限改为 777 好了