本文来自刘兆贤的博客_CSDN博客-Java高级,Android旅行,Android基础领域博主 ,引用必须注明出处!
应用启动过程:
点击桌面应用图标后,Launcher进程通过aidl的方式,通知SystemServer进程,SystemServer进程通过socket通信通知Zygote进程,fork出进程App进程。
研究安卓已多年,一直在应用层做开发,Framework层只是看过,也就是大家常说的"底层",而高级一点的功能如热加载、处理器类型配置,必须得了解再深入些才好,Library、Runtime、Kernel层等;当然了解底层的原因,不是在于去做底层开发,而是更好的做应用层,使其功能更强大和完善。这里的底层是除应用层以外其他层。而Dalvik是什么,就是把各层串起来,处理安卓系统和服务的一个计算机。
Dalvik这个名字,是创始人的祖先生存过一个小村庄的名字,大概为纪念先人的原因,这个村庄位于冰岛。前面也有讲这个虚拟机是专门为移动设备,即内存小、计算能力低、运行标准要求高提供的嵌入式设备,正因为克服如此多的问题,以其优良的性能出现在世人面前,才受到众多厂商的追捧,前有HTC、摩托罗拉,后来阿里云、小米;越来越追求代码层的优化,更好的解决方案,更快的解释、加载速度,更好的体验和兼容性,来抵消硬件设备带来的价格冲击-这也是国内厂商,应对众多街机的一种战略手段,以数十万上百万的出厂设备*单利-有限的研发力量价格=最终厂家利润,假设每件研发投入100万,价格降低5块,则收益至少达到平衡或500万以上;个人不太认同这种恶性竞争,逼死开发的策略,商品应该优质高价,让消费者使用安全放心,带给的是心理的安全感、舒适感、品牌感知度,以及强大的功能,像IPhone一样,让生活归生活,功能归功能;总之从厂商竞争情况来说,个人觉得华为做的最好。但万变不离其宗,产品总是不完善的,需要维护和升级,以维持其对于公众的领先地位,因此理解虚拟机,有助于从全局出发,提出更好的优化或解决方案,为消费者提供更好的产品。
闲话这么多,进入正题。Dalvik来自于JVM,大多数的java程序都可以执行(为什么说大多数,因为它退出JSF标准,按说1.6以后是否全面的支持Java,这事能肯定)。前面对JVM有过讲解,它基于堆栈,处理代码指令,需要不断的从主内存复制到临时内存,然后操作完再存回去,有寄存器但仅限于虚拟机自己使用;而Dalvik基于寄存器,代码的执行本身就依赖于寄存器,且避免过多的存取,字节码指令减少47%,访问次数减少37%,因此执行速度更快。但寄存器有一个缺陷,只有65536个,每个32位,即总共256k,因此它还需要另一种文件Odex的支持。说到它,就得先讲dex文件,我们都知道java文件被编译后形成.class文件,这种文件符合JVM的执行规则;而Dalvik则把.class文件使用dx工具压缩形成dex文件,它符合寄存器的执行规则,同时又是对原数据进行过优化,共享共同数据,降低冗余,使用代码结构紧凑,因而包大小大约为同类型jar文件的50%。
Dex文件的格式与前面讲的类文件格式类似,可以对比着看:有基本数据类,如byte占8位,表示1byte的有符号数,ubyte同样,但表示无符号数;也有文件结构,也有字符串索引,字段索引,方法索引,类型索引,类定义,多的是原型数据索引,连接数据区等;同时header信息里也存着魔数,文件总长度,以上各种索引及类型的个数、地址等,索引除公用的是绝对位置,其他均为相对位置。数据的存放。Dalvik字节码总共有226条,使用时会用一个hash指令表来存储,格式如 B|A|op 12x 第一个是指令,第二个是缩写,用来说明它的操作逻辑。
Odex文件是为了提高程序执行速度而做的本地缓存,一般存在data/dalvik-cache/xxx.odex,这个文件已经由寄存器加载时帮忙做过字节码校验、空方法消除、替换优化等工作,执行时优化解释odex,没有再执行dex