<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>诗意代码 - PoemCode &#187; Android</title>
	<atom:link href="http://www.poemcode.net/tag/android/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.poemcode.net</link>
	<description>These codes, As beautiful as poetry!</description>
	<lastBuildDate>Sun, 05 Feb 2012 13:10:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Android Application Framework Outside, Service Understanding : 4</title>
		<link>http://www.poemcode.net/2011/09/android-service-understanding-4/</link>
		<comments>http://www.poemcode.net/2011/09/android-service-understanding-4/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 09:12:14 +0000</pubDate>
		<dc:creator>Xu Haojie</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://www.poemcode.net/?p=2349</guid>
		<description><![CDATA[<div class="wp-caption alignright" style="width: 76px"><img class="size-full wp-image-521" title="Android" src="http://www.poemcode.net/wp-content/uploads/2009/09/android.gif" alt="Android" width="76" height="90" /></div>
在上文当中提到的service命令，它是如何获得服务的信息呢？这个这个仅为275行的简单程序（framework/base/cmds/service/service.cpp）并未有什么特别神奇的地方，从本质上它对服务信息一无所知，所有的信息都是通过IPC获得。

IPC（Inter Process Communication）几乎总是伴随着Service出现，--不论是系统服务，还是应用服务，因为服务运行的进程大部分和应用运行的进程不同。

Android有意淡化IPC，甚至使其透明，就连Android Dev Guide也只是对IPC只做简明的解释说明，Android这样做的目的是降低应用开发的技术门槛，使开发者更多关注业务逻辑等商业价值点。

<em>注意：RPC的全称为Remote Procedure Call，虽然和IPC只有一字之差，但并不相同。</em>

IPC只是一种概念，实现IPC的方式有多种，例如在linux上你可以使用socket等，而Android中则采用了Binder。]]></description>
			<content:encoded><![CDATA[<p><small>这是一篇旧文了，写于二零一零年七月至九月期间。当时我正在OPPO，完了电纸书项目，刚刚转入公司战略级项目，受命专职钻研Android Framework。本文即为当时的工作成果，曾以此为蓝本，组织了内部培训。本文成文后半月，我因不可抗拒原因，离开了OPPO，对Framework的研究中断，遂失去了一次专心研究Android的良机，深感痛惜。今日我把它晒出来，一来是温故旧知，二来帮助他人，但受限于既有知识，对Android的理解依旧是囫囵吞枣，文中谬误之处再所难免，恳请读者指正。<br />
</small></p>
<h2>Contents</h2>
<ol>
<li>Forward</li>
<li>Android Startup</li>
<li>Service Overview</li>
<ol>
<li>Application Service</li>
<li>Android Service</li>
<li>Native Service</li>
<li>System (Linux) Service</li>
</ol>
<li>Manage Service</li>
<ol>
<li>Manage Android Service</li>
<li>Behind ServiceManager Class</li>
<li>Manage Native Service</li>
<li>Behind defaultServiceManager</li>
</ol>
<li>Inter Process Communication</li>
<ol>
<li>From Java to Native</li>
<li>What’s BpBinder</li>
<li>What’s BBinder</li>
</ol>
</ol>
<h2>Inter Process Communication</h2>
<p>在上文当中提到的service命令，它是如何获得服务的信息呢？这个这个仅为275行的简单程序（framework/base/cmds/service/service.cpp）并未有什么特别神奇的地方，从本质上它对服务信息一无所知，所有的信息都是通过IPC获得。</p>
<p>IPC（Inter Process Communication）几乎总是伴随着Service出现，&#8211;不论是系统服务，还是应用服务，因为服务运行的进程大部分和应用运行的进程不同。</p>
<p>Android有意淡化IPC，甚至使其透明，就连Android Dev Guide也只是对IPC只做简明的解释说明，Android这样做的目的是降低应用开发的技术门槛，使开发者更多关注业务逻辑等商业价值点。</p>
<p><em>注意：RPC的全称为Remote Procedure Call，虽然和IPC只有一字之差，但并不相同。</em></p>
<p>IPC只是一种概念，实现IPC的方式有多种，例如在linux上你可以使用socket等，而Android中则采用了Binder。</p>
<h3>From Java to Native</h3>
<p>图表19展现的是ServiceManagerNative等相关类的结构，IPC/Binder的影子出现在了最后的位置。</p>
<p>那么Binder又是怎么样实现IPC呢？任何试图用一个模糊、新颖的概念来解释原有问题的行为，是一种混淆视听、忽悠人的伎俩，这不是探求真知的的态度。由于Service Manager本身也是一种服务，也是使用IPC的实例之一，以下就以Service Manager为例来进行追踪。</p>
<div id="attachment_2355" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/09/code-19.png" alt="" title="code-19" width="650" height="428" class="size-full wp-image-2355" /><p class="wp-caption-text">图表 19</p></div>
<p>图表20是Servcei Manager的C++层相关类的类图（Class Diagram）。</p>
<div id="attachment_2356" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/09/code-20.png" alt="" title="code-20" width="650" height="418" class="size-full wp-image-2356" /><p class="wp-caption-text">图表 20</p></div>
<p>从图表20可以看出，B(n)ServiceManager和BpServiceManager都是IServiceManager的子类。BpServiceManager是为在被调用时准备的代理对象，而BServiceManager则是真正的实现对象。</p>
<div id="attachment_2357" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/09/code-21.png" alt="" title="code-21" width="650" height="140" class="size-full wp-image-2357" /><p class="wp-caption-text">图表 21 （frameworks/base/cmd/runtime/ServiceManager.cpp）</p></div>
<p>图表21展现的是实现添加服务的真实实现代码。当系统将IPC请求分发给实现对象时，首先是通过BBinder的transact方法，然后转发给实现对象的onTransact方法。</p>
<h3>What’s BpBinder</h3>
<p>IBinder是对跨进程对象的抽象，在Android中代码注释是这样描述的：</p>
<blockquote><p>(IBinder is) Base class and low-level protocol for a remotable object. You can drive from this class to create an object for which processes can hold references to it. Communication between processes (method calls, property get and set) is down through a low-level protocol implemented on top of the transact() API.</p></blockquote>
<p>IBinder当中有一个关键的函数即transact，如图表22所示。</p>
<div id="attachment_2358" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/09/code-22.png" alt="" title="code-22" width="650" height="71" class="size-full wp-image-2358" /><p class="wp-caption-text">图表 22（frameworks/base/include/binder/IBinder.h）</p></div>
<p>通过图表20可以知道，BpBinder是IBinder的子类，那么BpBinder是怎样实现这个方法的呢？</p>
<div id="attachment_2359" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/09/code-23.png" alt="" title="code-23" width="650" height="203" class="size-full wp-image-2359" /><p class="wp-caption-text">图表 23（frameworks/base/libs/binder/BpBinder.cpp）</p></div>
<p>通过图表23可以知道，BpBinder实际上调用了IPCThreadState的transact方法。</p>
<h3>What’s BBinder</h3>
<p>IBinder的另一个子类为BBinder，那么它的transact方法又是怎么样的呢？如图表24所示。</p>
<div id="attachment_2360" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/09/code-24.png" alt="" title="code-24" width="650" height="289" class="size-full wp-image-2360" /><p class="wp-caption-text">图表 24（frameworks/base/libs/binder/Binder.cpp）</p></div>
<p>从上面可以看出transact实际上也没有完成多少工作，其把核心的操作留给了onTransact方法去做，虽然BBinder类实现了onTransact，但实际上这个方法是一定要被子类重写（override）的。例如，在图表20中，BBinder的子类BnServiceManager是这样重写该方法的 。</p>
<div id="attachment_2361" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/09/code-25.png" alt="" title="code-25" width="650" height="163" class="size-full wp-image-2361" /><p class="wp-caption-text">图表 25（frameworks/base/libs/binder/IServiceManager.cpp）</p></div>
<p>由此可以知道，服务真正实现代码是在BBinder的子类中，这才是真正做事的角色，而BpBinder则只是一个代理角色，&#8211;这也难怪其名称中带有一个p，大概就是Proxy的意思吧。</p>
<hr />
<p><small>到此为止，全文结束。可以坦诚地讲，这篇博文是不完整的，并没有将Service解释清楚，希望自己以后能有机会完善这部分的知识。再次声明，本文只供参考，不做权威性解读。</small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.poemcode.net/2011/09/android-service-understanding-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Application Framework Outside, Service Understanding : 3</title>
		<link>http://www.poemcode.net/2011/08/android-service-understanding-3/</link>
		<comments>http://www.poemcode.net/2011/08/android-service-understanding-3/#comments</comments>
		<pubDate>Tue, 30 Aug 2011 03:09:58 +0000</pubDate>
		<dc:creator>Xu Haojie</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://www.poemcode.net/?p=2318</guid>
		<description><![CDATA[<div class="wp-caption alignright" style="width: 76px"><img class="size-full wp-image-521" title="Android" src="http://www.poemcode.net/wp-content/uploads/2009/09/android.gif" alt="Android" width="76" height="90" /></div>
大千世界，具体到社会运作，抽象至软件运行，不以规矩，不成方圆 ，所有的一切都要接受约束和管理，在一系列规则下生存。那么Android中众多的service又是如何被管理的？

<h3>Manage Android Service</h3>

Service要在Android系统中发挥作用，首先要解决一个问题：Android是如何使其成为系统服务的。

以AlarmManagerService为例，观察构造函数的调用位置，那么可以发现其出现在com.android.server.ServerThread，与此相似，很多Service的构造函数都出现在com.android.server.ServerThread。但是，令人奇怪的是，无论如何也找不到ServerThread.java这么一个文件，实际上它躲藏在SystemServer.java中。

<em>注意：多个class声明在同一个文件里是一种不值得推荐的做法，尽管Android中这种做法并不少见。</em>]]></description>
			<content:encoded><![CDATA[<p><small>这是一篇旧文了，写于二零一零年七月至九月期间。当时我正在OPPO，完了电纸书项目，刚刚转入公司战略级项目，受命专职钻研Android Framework。本文即为当时的工作成果，曾以此为蓝本，组织了内部培训。本文成文后半月，我因不可抗拒原因，离开了OPPO，对Framework的研究中断，遂失去了一次专心研究Android的良机，深感痛惜。今日我把它晒出来，一来是温故旧知，二来帮助他人，但受限于既有知识，对Android的理解依旧是囫囵吞枣，文中谬误之处再所难免，恳请读者指正。<br />
</small></p>
<h2>Contents</h2>
<ol>
<li>Forward</li>
<li>Android Startup</li>
<li>Service Overview</li>
<ol>
<li>Application Service</li>
<li>Android Service</li>
<li>Native Service</li>
<li>System (Linux) Service</li>
</ol>
<li>Manage Service</li>
<ol>
<li>Manage Android Service</li>
<li>Behind ServiceManager Class</li>
<li>Manage Native Service</li>
<li>Behind defaultServiceManager</li>
</ol>
<li>Inter Process Communication</li>
<ol>
<li>From Java to Native</li>
<li>What’s BpBinder</li>
<li>What’s BBinder</li>
</ol>
</ol>
<h2>Manage Service</h2>
<p>大千世界，具体到社会运作，抽象至软件运行，不以规矩，不成方圆 ，所有的一切都要接受约束和管理，在一系列规则下生存。那么Android中众多的service又是如何被管理的？</p>
<h3>Manage Android Service</h3>
<p>Service要在Android系统中发挥作用，首先要解决一个问题：Android是如何使其成为系统服务的。</p>
<p>以AlarmManagerService为例，观察构造函数的调用位置，那么可以发现其出现在com.android.server.ServerThread，与此相似，很多Service的构造函数都出现在com.android.server.ServerThread。但是，令人奇怪的是，无论如何也找不到ServerThread.java这么一个文件，实际上它躲藏在SystemServer.java中。</p>
<p><em>注意：多个class声明在同一个文件里是一种不值得推荐的做法，尽管Android中这种做法并不少见。</em></p>
<p>ServerThread并不是一个多么神秘的类，仅仅是java.lang.Thread的子类，其使命就是在新起的线程上实例化服务，然后把它们加入到android.os.ServiceManager中进行统一管理，如图表7所展示。</p>
<div id="attachment_2321" class="wp-caption aligncenter" style="width: 628px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-7.png" alt="" title="code-7" width="618" height="56" class="size-full wp-image-2321" /><p class="wp-caption-text">图表 7（frameworks/base/services/java/com/anroid/server/SystemServer.java）</p></div>
<p>一个不被使用的service是没有价值的，在解决了如何成为系统服务之后，还需要解决另外一个问题，那就是如何获取系统服务。前面提到ServiceManager提供了addService方法实现了向系统中添加服务的功能，同样它提供了getService方法实现从系统中获取服务的功能。</p>
<p>以android.app.ContextImpl中获取电源管理服务为例，首先从getService方法中获取服务对应的IBinder，然后通过asInterface方法获得服务实例。通用做法同图表8所示。</p>
<div id="attachment_2324" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-8.png" alt="" title="code-8" width="650" height="182" class="size-full wp-image-2324" /><p class="wp-caption-text">图表 8（frameworks/base/core/java/android/app/ContextImpl.java）</p></div>
<h3>Behind ServiceManager Class</h3>
<p>ServerThread在SystemServer的init2方法中被启动，奇怪的是，却怎么也不见init2是在哪里被调用的？</p>
<p>SystemServer的main方法是入口，libandroid_servers.so被加载进来以后调用其中的本地方法init1。通过过com_android_server_SystemServer.cpp 可以知道其把init1的调用委托给了system_init方法，而这个方法是在system_init.cpp中实现的，在该方法的末尾，可以看到如下信息：</p>
<div id="attachment_2325" class="wp-caption aligncenter" style="width: 655px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-9.png" alt="" title="code-9" width="645" height="44" class="size-full wp-image-2325" /><p class="wp-caption-text">图表 9（frameworks/base/cmd/system_server/library/system_init.cpp）</p></div>
<p>图表9解释了玄机，在init1执行将结束时，SystemServer的init2被调用。ServerThread被调用start方法以后，进入到run方法当中，服务被创建，通过ServiceManager.addService添加到IServiceManager当中。</p>
<p>但是也引发了一个新的疑问：ServiceManager是如何实现管理功能的呢？</p>
<p>经过静态代码分析，可以发现ServiceManager.java并不是实现服务管理的真正“主谋”，ServiceManager将调用转发给了ServiceManagerNative，而ServiceManagerNative又将其转包，交给了ServiceManagerProxy。</p>
<p>从代码上看，ServiceManagerProxy最终还是借助IBinder完成了它的职责，如图表10所示。</p>
<div id="attachment_2326" class="wp-caption aligncenter" style="width: 637px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-10.png" alt="" title="code-10" width="627" height="201" class="size-full wp-image-2326" /><p class="wp-caption-text">图表 10（frameworks/core/java/android/os/ServiceManagerNative.java）</p></div>
<p>我们对service使用IPC感到司空见惯，现在发现ServiceManager一样离不开IPC，&#8211;是不是ServiceManager也是一种service呢？通常当看到IPC后，思考就停止了，这已经到了Android的底层。但是，浅尝则止永远不会进步。对问题穷根究底，就会发问：IPC到底是怎么运作的？</p>
<h3>Manage Native Service</h3>
<p>由上可见，ServiceManager类提供了管理Android Service的功能，但是，对于Native Service又是如何处理呢？</p>
<p>在图表5中，MeideaPlayerService调用了instantiate方法，注释中标明“Start the media playback service”，这表明服务被开启了，如果进入到instantiate方法，可以发现：</p>
<div id="attachment_2327" class="wp-caption aligncenter" style="width: 655px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-11.png" alt="" title="code-11" width="645" height="80" class="size-full wp-image-2327" /><p class="wp-caption-text">图表 11（frameworks/media/libmediaplayerservice/MediaPlayerService.cpp）</p></div>
<p>图表11展示了Native Service是如何被加入到ServiceManager中进行管理，接下图表12展现了如何从ServiceManager中获取Native Service。</p>
<div id="attachment_2328" class="wp-caption aligncenter" style="width: 639px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-121.png" alt="" title="code-12" width="629" height="76" class="size-full wp-image-2328" /><p class="wp-caption-text">图表 12（frameworks/base/cmd/stagefright/stagefright.cpp）</p></div>
<h3>Behind defaultServiceManager</h3>
<p>出现在上节当中的defaultServiceManager是如何得到IServiceManager的呢？这就要追踪到源码了。</p>
<div id="attachment_2329" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-13.png" alt="" title="code-13" width="650" height="248" class="size-full wp-image-2329" /><p class="wp-caption-text">图表 13 (framework/base/libs/binder/IServiceManager.cpp)</p></div>
<p>当进程首次运行到图表13时，gDefaultServiceManager肯定是为NULL，因此肯定是要执行ProcessState::self()。</p>
<div id="attachment_2330" class="wp-caption aligncenter" style="width: 553px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-14.png" alt="" title="code-14" width="543" height="144" class="size-full wp-image-2330" /><p class="wp-caption-text">图表 14 (framework/base/libs/binder/ProcessState.cpp)</p></div>
<p>图表14可以得出一个结论：一个进程只有一个ProcessState对象，而在创建对象的过程中，调用open_driver方法为mDriverFD赋值，也就是在open_driver中，进程打开了/dev/binder。</p>
<p>回过头来再来看ProcessState类的成员函数getContextObject，根据代码的执行流程，可以判断出其最终进入到成员函数getStrongProxyForHandle中。</p>
<div id="attachment_2331" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-15.png" alt="" title="code-15" width="650" height="516" class="size-full wp-image-2331" /><p class="wp-caption-text">图表 15 (framework/base/libs/binder/ProcessState.cpp)）</p></div>
<p>由以上的代码来看，最终得到的是BpBinder的指针，那么接下来的interface_cast又到底做了什么呢？</p>
<div id="attachment_2332" class="wp-caption aligncenter" style="width: 605px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-16.png" alt="" title="code-16" width="595" height="91" class="size-full wp-image-2332" /><p class="wp-caption-text">图表 16（framework/base/include/binder/IInterface.h）</p></div>
<p>至此真相即将揭开了，asInterface如图表17所示。</p>
<div id="attachment_2333" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-17.png" alt="" title="code-17" width="650" height="396" class="size-full wp-image-2333" /><p class="wp-caption-text">图表 17 （framework/base/include/binder/IInterface.h）</p></div>
<p>那么这个宏到底是怎么使用的呢？</p>
<div id="attachment_2334" class="wp-caption aligncenter" style="width: 660px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-18.png" alt="" title="code-18" width="650" height="22" class="size-full wp-image-2334" /><p class="wp-caption-text">图表 18（framework/base/libs/binder/IServiceManager.cpp）</p></div>
<p>在从中可以看到，最后得到的是一个BpServiceManager</p>
]]></content:encoded>
			<wfw:commentRss>http://www.poemcode.net/2011/08/android-service-understanding-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Application Framework Outside, Service Understanding : 2</title>
		<link>http://www.poemcode.net/2011/08/android-service-understanding-2/</link>
		<comments>http://www.poemcode.net/2011/08/android-service-understanding-2/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 07:21:57 +0000</pubDate>
		<dc:creator>Xu Haojie</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://www.poemcode.net/?p=2259</guid>
		<description><![CDATA[<div class="wp-caption alignright" style="width: 76px"><img class="size-full wp-image-521" title="Android" src="http://www.poemcode.net/wp-content/uploads/2009/09/android.gif" alt="Android" width="76" height="90" /></div>
Service一词在Android中出现的概率非常大，以致不同上下文（Context）在着较大差异。如果详细划分，则可以分为四类：Application Service、Android Service、Native Service、System (Linux) Service。

尽管存在着差异，但是透过Reference中对Application Service的描述，仍旧可以概括出所有Service的本质：
<blockquote>A Service is an (application) component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.</blockquote>]]></description>
			<content:encoded><![CDATA[<p><small>这是一篇旧文了，写于二零一零年七月至九月期间。当时我正在OPPO，完了电纸书项目，刚刚转入公司战略级项目，受命专职钻研Android Framework。本文即为当时的工作成果，曾以此为蓝本，组织了内部培训。本文成文后半月，我因不可抗拒原因，离开了OPPO，对Framework的研究中断，遂失去了一次专心研究Android的良机，深感痛惜。今日我把它晒出来，一来是温故旧知，二来帮助他人，但受限于既有知识，对Android的理解依旧是囫囵吞枣，文中谬误之处再所难免，恳请读者指正。<br />
</small></p>
<h2>Contents</h2>
<ol>
<li>Forward</li>
<li>Android Startup</li>
<li>Service Overview</li>
<ol>
<li>Application Service</li>
<li>Android Service</li>
<li>Native Service</li>
<li>System (Linux) Service</li>
</ol>
<li>Manage Service</li>
<ol>
<li>Manage Android Service</li>
<li>Behind ServiceManager Class</li>
<li>Manage Native Service</li>
<li>Behind defaultServiceManager</li>
</ol>
<li>Inter Process Communication</li>
<ol>
<li>From Java to Native</li>
<li>What’s BpBinder</li>
<li>What’s BBinder</li>
</ol>
</ol>
<h2>Service Overview</h2>
<p>Service一词在Android中出现的概率非常大，以致不同上下文（Context）在着较大差异。如果详细划分，则可以分为四类：Application Service、Android Service、Native Service、System (Linux) Service。</p>
<p>尽管存在着差异，但是透过Reference中对Application Service的描述，仍旧可以概括出所有Service的本质：</p>
<blockquote><p>A Service is an (application) component representing either an application&#8217;s desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.</p></blockquote>
<h3>Application Service</h3>
<p>通过继承android.app.Service而创建服务，是应用开发人员最为熟悉的应用场景。此时的服务通常称为应用服务（Application Service），其和Activity、BroadcastReceiver和ContentProvider一起构成了Android四大应用组件（Application Component）。</p>
<p>一般应用中都会自行创建自己的服务，在SDK的sample里，示例ApiDemos中提供了Remote Service Binding详细演示了如何创建和使用。图表2展现其中各个类之间的关系。</p>
<p><em>注意：IRemoteService、ISecondary、IRemoteServiceCallback三个类还有一个共同的父类就是IInterface，图中没有展现，但这一点对理解IPC非常重要。</em></p>
<div id="attachment_1235" class="wp-caption aligncenter" style="width: 560px"><img src="http://www.poemcode.net/wp-content/uploads/2010/05/Remote-Service-Binding.png" alt="Remote Service Binding" title="Remote Service Binding" width="550" height="386" class="size-full wp-image-1235" /><p class="wp-caption-text">图表2 Remote Service Binding</p></div>
<h3>Android Service</h3>
<p>Android源代码中，在framework/base/services路径下可以看到各种以XxxService形式命名的java文件，但没有继承自android.app.Servic。透过文件组织结构，先来对其概貌做一个了解，如图表3所示。</p>
<div id="attachment_2279" class="wp-caption aligncenter" style="width: 458px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-12.png" alt="" title="code-1" width="448" height="250" class="size-full wp-image-2279" /><p class="wp-caption-text">图表3</p></div>
<p>抛开jni和tests两个文件夹不谈，java文件夹诸如“XxxService”一类的文件共有三十五个之多，如图表4所示。</p>
<div id="attachment_2281" class="wp-caption aligncenter" style="width: 525px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-21.png" alt="" title="code-2" width="515" height="631" class="size-full wp-image-2281" /><p class="wp-caption-text">图表 4</p></div>
<p>提醒：如此多的Service，但它们的包名（package name）却是com.android.server，而不是com.android.service。</p>
<p>如此众多的Service共同构成了Android Service（找不到更合适的名字，考虑过使用Java Service以便和下文Native Service对应，但最终没有采用）。</p>
<p>严格地讲，并不是每一个包含了Service字眼的Class就是一个Android Service。图表4并不能如实反映系统某一个时刻Service运行的真实情况，Android提供了一个很棒的同名工具—service。</p>
<p>使用service list命令了解当前有哪些服务在运行，效果如图表5所示（部分结果）。除list外，service还可以搭配check和call实现其他功能，是帮助分析Service不错的利器。</p>
<div id="attachment_2282" class="wp-caption aligncenter" style="width: 571px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-3.png" alt="" title="code-3" width="561" height="206" class="size-full wp-image-2282" /><p class="wp-caption-text">图表 5</p></div>
<h3>Native Service</h3>
<p>Android的应用编程语言（Application Program Language）为Java，这意味着开发人员在享用Java的便捷的同时，也在承受Java的局限、效率等弊病。在Android中并不是所有的Service都是用Java来编写，例如AudioPolicyService。</p>
<p>所谓Native Service是指采用C++/C来实现的Service，透过system_init.cpp中的system_init方法可以知道，在Android一共有SurfaceFlinger、AudioFlinger、MediaPlayerService、CameraService和AudioPolicyService。</p>
<div id="attachment_2283" class="wp-caption aligncenter" style="width: 560px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/code-4.png" alt="" title="code-4" width="550" height="323" class="size-full wp-image-2283" /><p class="wp-caption-text">图表 6</p></div>
<h3>System (Linux) Service</h3>
<p>Android的开机流程是加电后执行bootloader，接着被引导进入kernel，完成之后启动用户进程init。此时系统将按照init.rc来启动服务，包括console、adbd、servicemanager、vold、zygote、bootanim等。</p>
<p>注意：servicemanager就是下文中管理各类服务的服务！</p>
<p>这些在底层活动的daemon process，称为System Service受之无愧。但是由于和Application，甚至和Framework都关系非常少，所以暂不用理会它。</p>
<p>因为用的少，System Service这一名字常常被挪做他用，很多时候用来指代Android Service或Native Service，以至于我认为Linux Service这个名字更适合它。 </p>
]]></content:encoded>
			<wfw:commentRss>http://www.poemcode.net/2011/08/android-service-understanding-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Application Framework Outside, Service Understanding : 1</title>
		<link>http://www.poemcode.net/2011/08/android-service-understanding-1/</link>
		<comments>http://www.poemcode.net/2011/08/android-service-understanding-1/#comments</comments>
		<pubDate>Thu, 25 Aug 2011 09:22:52 +0000</pubDate>
		<dc:creator>Xu Haojie</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://www.poemcode.net/?p=2201</guid>
		<description><![CDATA[<div class="wp-caption alignright" style="width: 76px"><img class="size-full wp-image-521" title="Android" src="http://www.poemcode.net/wp-content/uploads/2009/09/android.gif" alt="Android" width="76" height="90" /></div>
从2007年11月5日Google首次发布Android以来，这个绿色机器人  Open Source、体系架构卓越、应用开发便捷等亮点日益引起业界的浓厚兴趣，到目前为止陆续发布了1.1、1.5、1.6、2.0、2.1和2.2等版本，日趋完善的进取势头带动了移动互联网一股新的热潮。

文档名 Android Framework Outside，原本是打算用Inside，但是由于Framework内容繁复，如果用Inside，未免显得自负，况且我也无法做到了如指掌、洞若观火，因此取名Outside，表示这只是一知半解。

由于无法在短时间内面面俱到，目前优先选择其中的Service部分进行学习，整理成Service Understanding。但尽管Service只是Framework中一个组成部分，仍旧体积庞大，对其内容继续筛选后，选择WindowManagerService和ActivityManagerService进行重点研究。]]></description>
			<content:encoded><![CDATA[<p><small>这是一篇旧文了，写于二零一零年七月至九月期间。当时我正在OPPO，完了电纸书项目，刚刚转入公司战略级项目，受命专职钻研Android Framework。本文即为当时的工作成果，曾以此为蓝本，组织了内部培训。本文成文后半月，我因不可抗拒原因，离开了OPPO，对Framework的研究中断，遂失去了一次专心研究Android的良机，深感痛惜。今日我把它晒出来，一来是温故旧知，二来帮助他人，但受限于既有知识，对Android的理解依旧是囫囵吞枣，文中谬误之处再所难免，恳请读者指正。<br />
</small></p>
<h2>Contents</h2>
<ol>
<li>Forward</li>
<li>Android Startup</li>
<li>Service Overview</li>
<ol>
<li>Application Service</li>
<li>Android Service</li>
<li>Native Service</li>
<li>System (Linux) Service</li>
</ol>
<li>Manage Service</li>
<ol>
<li>Manage Android Service</li>
<li>Behind ServiceManager Class</li>
<li>Manage Native Service</li>
<li>Behind defaultServiceManager</li>
</ol>
<li>Inter Process Communication</li>
<ol>
<li>From Java to Native</li>
<li>What’s BpBinder</li>
<li>What’s BBinder</li>
</ol>
</ol>
<p><H2>Forword</H2></p>
<p>从2007年11月5日Google首次发布Android以来，这个绿色机器人  Open Source、体系架构卓越、应用开发便捷等亮点日益引起业界的浓厚兴趣，到目前为止陆续发布了1.1、1.5、1.6、2.0、2.1和2.2等版本，日趋完善的进取势头带动了移动互联网一股新的热潮。</p>
<div id="attachment_577" class="wp-caption alignleft" style="width: 86px"><img src="http://www.poemcode.net/wp-content/uploads/2009/09/android.gif" alt="" title="Android" width="76" height="90" class="size-full wp-image-577" /><p class="wp-caption-text">Android</p></div>
<p>文档名 Android Framework Outside，原本是打算用Inside，但是由于Framework内容繁复，如果用Inside，未免显得自负，况且我也无法做到了如指掌、洞若观火，因此取名Outside，表示这只是一知半解。</p>
<p>由于无法在短时间内面面俱到，目前优先选择其中的Service部分进行学习，整理成Service Understanding。但尽管Service只是Framework中一个组成部分，仍旧体积庞大，对其内容继续筛选后，选择WindowManagerService和ActivityManagerService进行重点研究。</p>
<p>路漫漫其修远，吾当上下求索，我将当前个人理解整理成文，一来承前启后，二来分享所知。但囿于个人能力，对其理解也是管中窥豹，所言所述，并非真理，差错之处，在所难免，欢迎指正，与我联系发E-Mail至PoemCode@Gmail.com，或访问www.PoemCode.net留言。</p>
<p>学习过程中，网络给了我非常大的帮助，非常感谢乐于分享的Androider，他们当中有：</p>
<ol>
<li><a href="http://xy0811.spaces.live.com" target="blank">http://xy0811.spaces.live.com</a></li>
<li><a href="http://blog.csdn.net/maxleng" target="blank">http://blog.csdn.net/maxleng</a></li>
<li><a href="http://hi.baidu.com/albertchen521" target="blank">http://hi.baidu.com/albertchen521</a></li>
<li><a href="http://www.limodev.cn/blog" target="blank">http://www.limodev.cn/blog</a></li>
</ol>
<h2>Android Startup</h2>
<blockquote><p>
我生从何来，死往何处？我为何要出现在这个世界上？我的出现对这个世界来说意味着什么？是世界选择了我，还是我选择了世界？<br />
<font style="float:right">&#8211;《武林外传》</font>
</p></blockquote>
<p>生命从孕育到诞生，经过成长，开枝散叶，终了油尽灯枯。生命如此，万物亦如此？我们往往着眼当下，无知过往和未来，以为看得明明白白，不料这只是生命期（lifetime）中一个片段。</p>
<p>如果我们以生命期(lifetime)来看一段代码，那么其被加入到内存那一刻，应该被视为孕育，内存被释放的那一瞬间则是其终结。同样的眼光来看一个OS，从上电开始，各类代码被执行，创建形形色色的进程，到系统接到关机指令，杀死所有，断电为止，这一个过程就是其生命期（lifetime），Windows如此，Android如此，我想Matrix 也如此。每一次开、关机都是其生命期（lifteime）的重复。</p>
<p>本章节内容将围绕Android的生命期（lifetime）中的一个片段：从我们按下电源键到解锁后看到桌面。本章节为接下来要讲述的Service和Service Manager做前期的预备知识。</p>
<div id="attachment_2229" class="wp-caption aligncenter" style="width: 676px"><img src="http://www.poemcode.net/wp-content/uploads/2011/08/android_startup.png" alt="Android Startup" title="Android Startup" width="666" height="368" class="size-full wp-image-2229" /><p class="wp-caption-text">图表1 Android Startup</p></div>
<p>图表1为采用UML中的活动图（Activity Diagram），展现这段要关注的生命期（lifetime）片段。</p>
<p>在第一个环节，bootloader首先被执行，其有三种模式：normal、recovery和fastboot，至于到底是进入到哪种模式，取决于当时用户的操作，以HTC G1为例，只按下Power键，则进入到normal；Power+Home键，则进入recovery；Power+Camera，则进入fastboot。以下流程假定进入normal模式。</p>
<p>Kernel是由bootloader加载的，为第二个环节，完毕以后，由内核启动init，这是一用户进程，执行内容由init.rc文件决定，此为第三个环节。在第三个环节中，有诸多服务会被创建，也就是后文中所提到的sytem/linux service中，其中有管理各类服务的servicemanager，还有作为java层基石的zygote，等等。</p>
<p>接下来SystemService被启动，负责创建后文所提到的Android/Native Service，其中那个包括管理Activity的ActivityManagerService，负责管理Window的WindowManagerService，负责电源管理的PowerManagerService等。</p>
<p>剩余的事情就是ActivityManagerService发出systemReady的信号，桌面Launcher，第三方随机启动的应用开始执行。</p>
<p>同样WindowManagerService也会发出systemReady信号，LockScreen随即启动。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.poemcode.net/2011/08/android-service-understanding-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android ProGuard: Please correct the above warnings first</title>
		<link>http://www.poemcode.net/2011/03/android-proguard-please-correct-the-above-warnings-first/</link>
		<comments>http://www.poemcode.net/2011/03/android-proguard-please-correct-the-above-warnings-first/#comments</comments>
		<pubDate>Fri, 11 Mar 2011 06:26:43 +0000</pubDate>
		<dc:creator>Xu Haojie</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://www.poemcode.net/?p=1860</guid>
		<description><![CDATA[<div class="wp-caption alignright" style="width: 76px"><img class="size-full wp-image-521" title="Android" src="http://www.poemcode.net/wp-content/uploads/2009/09/android.gif" alt="Android" width="76" height="90" /></div> 
编译与反编译，一对相辅相成的矛盾。反编译有时候会和不光彩的事情联系在一起，以致于编译者常常费劲心思，加大反编译的难度，比如采用混淆代码等方式。ProGuard正是这么一个工具：

<blockquote>
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure name.
</blockquote>]]></description>
			<content:encoded><![CDATA[<p>编译与反编译，一对相辅相成的矛盾。反编译有时候会和不光彩的事情联系在一起，以致于编译者常常费劲心思，加大反编译的难度，比如采用混淆代码等方式。ProGuard正是这么一个工具：</p>
<blockquote><p>
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure name.
</p></blockquote>
<p>Android SDK整合了ProGuard，并在文档中用了一个章节来描述如何使用它。依照文档来实施，多半没有问题，不过在我使用中遇到了一个问题：<br />
<samp><br />
 [proguard] Warning: there were 2 unresolved references to classes or interfaces.<br />
 [proguard]          You may need to specify additional library jars (using &#8216;-libraryjars&#8217;),<br />
 [proguard]          or perhaps the &#8216;-dontskipnonpubliclibraryclasses&#8217; option.<br />
 [proguard] Warning: there were 5 unresolved references to program class members.<br />
 [proguard]          Your input classes appear to be inconsistent.<br />
 [proguard]          You may need to recompile them and try again.<br />
 [proguard]          Alternatively, you may have to specify the options<br />
 [proguard]          &#8216;-dontskipnonpubliclibraryclasses&#8217; and/or<br />
 [proguard]          &#8216;-dontskipnonpubliclibraryclassmembers&#8217;.</p>
<p>BUILD FAILED<br />
/Users/xuhj/Develop/android-sdk-mac_x86/tools/ant/main_rules.xml:453: Please correct the above warnings first.<br />
</samp></p>
<p>依照以往的惯例，发生warning，可忽视之，只有看到error，才会小紧张一把。不过这次的warning导致了BUILD FAILED，这回问题大了。</p>
<p>按照提示，在proguard.cfg里，加入<code>-dontskipnonpubliclibraryclasses</code>，再试，还是有问题。</p>
<p>那就到<a href="http://proguard.sourceforge.net" target="blank">官网</a>找找答案吧，Manual -> Troubleshooting -> “Warning: can&#8217;t find referenced class”，找到这么一句话：<q>try your luck with the -ignorewarnings option, or even the -dontwarn option.</q>再对比日志信息，发现：<br />
<samp><br />
[proguard] Warning: net.poemcode.Digest: can&#8217;t find referenced class org.apache.CastleProvider<br />
</samp></p>
<p>打开proguard.cfg，加入<code>-dontwarn net.poemcode.**</code>，再次执行<kbd>ant release</kbd>，万事大吉。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.poemcode.net/2011/03/android-proguard-please-correct-the-above-warnings-first/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

