Android 综合揭秘 —— 全面剖释 Service 服务

引言

Service 服务是 Android 系统最常用的四大部件之一,Android 支持 Service 服务的原因主要目的有两个,一是简化后台任务的实现,二是实现在同一台设备当中跨进程的远程信息通信。
Service 服务主要分为 Local Service 本地服务与 Remote Service 远程服务两种,本地服务只支持同一进程内的应用程序进行访问,远程服务可通过AIDL(Android Interface Definition Language)技术支持跨进程访问。服务可以通过Context.startService()和Context.bindService()进行启动,一般Local Service本地服务可使用其中一种方法启动,但Remote Service远程服务只能使用Context.bindService()启动,而两种调用方式在使用场景与活动流程中都存在差异。还有通过多线程技术处理 Service 服务的延时操作等技术,下文将针对Android 系统的 Service 服务的一系列操作进行深入探讨。

 

 

目录

一、Service 服务的概念与说明

二、Service 服务的生命周期

三、Local Service 的应用原理与开发实例

四、通过多线程方式处理 Service 服务的延时性操作

五、浅谈 Remote Service 远程服务原理

 

 

一、Android Service的概念与说明

1.1 Service 服务的定义

Android Service 是 Android 平台最常用的部件之一,其概念与 Windows Service 类似,熟悉Windows开发的朋友应该对此概念会有所了解。当 Android 系统需要对现有的程序数据进行监听,或者对现有 Actitvity 提供数据服务支撑时,就会使用到 Android Service 。例如:对用户地理位置的检测,对SD卡定时扫描,对当地气候的定期检测都会使用到 Service 服务,Service 一般都是运行于后台,不需要用户界面支撑。Service 服务不会自动创建线程,如果开发人员没有为Service服务添加异步操作,那Service服务将运行于主线程当中。

1.2 Service 服务的类型

1.2.1 按照 Service 的生命周期模型一共分为两种类型

第一类是直接通过Context.startService()启动,通过Context.stopService() 结束Service,其特点在于调用简单,方便控制。缺点在于一旦启动了 Service 服务,除了再次调用或结束服务外就再无法对服务内部状态进行操控,缺乏灵活性。

第二类是通过Context.bindService()启动,通过Context.unbindService() 结束,相对其特点在运用灵活,可以通过 IBinder 接口中获取 Service 的句柄,对 Service 状态进行检测。

从 Android 系统设计的架构上看,startService() 是用于启动本地服务,bindService() 更多是用于对远程服务进行绑定。当然,也可以结合两者进行混合式应用,先通过startService()启动服务,然后通过 bindService() 、unbindService()方法进行多次绑定,以获取 Service 服务在不同状态下的信息,最后通过stopService()方法结束Service运行,在下面文章里将举例一一说明。

1.2.2 按照 Service 的寄存方式分为两种类型

本地服务 (Local Service) 寄存于当前的进程当中,当前进程结束后 Service 也会随之结束,Service 可以随时与 Activity 等多个部件进行信息交换。Service服务不会自动启动线程,如果没有人工调用多线程方式进行启动,Service将寄存于主线程当中。

远程服务 (Remote Service ) 独立寄存于另一进程中, 通过 AIDL (Android Interface Definition Language)接口定义语言,实现Android设备上的两个进程间通信(IPC)。AIDL 的 IPC 机制是基于 RPC (Remote Proceduce Call) 远程过程调用协议建立的,用于约束两个进程间的通讯规则,供编译器生成代码。进程之间的通信信息,首先会被转换成AIDL协议消息,然后发送给对方,对方收到AIDL协议消息后再转换成相应的对象,其使用方法在下文将会详细说明。

回到目录

二、Android Service 的生命周期

2.1 Service 服务的常用方法

方法  说明
void onCreate() 当Service被启动时被触发,无论使用Context.startServcie还是Context.bindService启动服务,在Service整个生命周期内只会被触发一次
int onStartCommand(Intent intent, int flags, int startId) 当通过Context.startService启动服务时将触发此方法,但当使用 Context.bindService 方法时不会触发此方法,其中参数 intent 是 startCommand 的输入对象,参数 flags 代表 service 的启动方式,参数 startId 当前启动 service 的唯一标式符。返回值决定服务结束后的处理方式,下文将再作详细说明。
void onStart(Intent intent,int startId) 2.0旧版本的方法,已被Android抛弃,不推荐使用,默认在onStartCommand 执行中会调用此方法
IBinder onBind(Intent intent) 使用 Context.bindService 触发服务时将调用此方法,返回一个IBinder 对象,在远程服务时可用于对 Service 对象进行远程操控
void onRebind(Intent intent) 当使用startService启动Service,调用bindService启动Service,且 onUnbind 返回值为 true 时,下次再次调用 Context.bindService 将触发方法
boolean onUnbind(Intent intent) 调用 Context.unbindService 触发此方法,默认返回 false, 当返回值 true 后,再次调用 Context.bindService 时将触发 onRebind 方法
void onDestory() 分三种情况:1.以Context.startService启动service,调用Context.stopService结束时触发此方法;2.以Context.bindService启动service,以Context.unbindService结束时触发此方法;3.先以Context.startService 启动服务,再用Context.bindService绑定服务,结束时必须先调用Context.unbindService解绑再使用Context.stopService结束service才会触发此方法。

表2.1

  • 细说onStartCommand 方法

由于手机的RAM、内部资源有限,所以很多Service都会因为资源不足而被Kill掉,这时候返回值就决定了Service被Kill后的处理方式,一般 int onStartCommand(intent,flags,startId)的返回值分为以下几种:

START_STICKY
如果service进程被kill掉,系统会尝试重新创建Service,如果在此期间没有任何启动命令被传递到Service,那么参数intent将为null。

START_NOT_STICKY
使用这个返回值时,如果在执行完onStartCommand()后,服务被异常kill掉,系统不会自动重启该服务。

START_REDELIVER_INTENT
使用这个返回值时,如果在执行完onStartCommand()后,服务被异常kill掉,系统会自动重启该服务,并将intent的值传入。

START_STICKY_COMPATIBILITY
START_STICKY的兼容版本,但不保证服务被kill后一定能重启。

而输入参数flags正是代表此次onStartCommand()方法的启动方式,正常启动时,flags默认为0,被kill后重新启动,参数分为以下两种:

START_FLAG_RETRY
代表service被kill后重新启动,由于上次返回值为START_STICKY,所以参数 intent 为null

START_FLAG_REDELIVERY
代表service被kill后重新启动,由于上次返回值为START_REDELIVER_INTENT,所以带输入参数intent

2.2 Service 的运作流程

上文曾经提到 Service 的启动方法有Context.startService(intent),Context.bindService(intent,serviceConnection,int) 两种,下面详细介绍一下它们工作流程。

当系统调用Context.startService()方法时,先会触发Service的onCreate()方法,这一般用于对Service的运行条件作初始化处理,且在Service的生命周期内只会被触发一次。然后系统将触发Service的onStartCommand()方法,用户每次调用startService()方法,都会触发onStartCommand()方法。之后,Service 除非在资源不足的情况下被系统 kill 掉,否则Service不会自动结束,直至系统调用Context.stopService()方法时,Service 才会结束。在Service结束时将自动启动onDestory()方法对运转中的Service作最后处理。

注意即使系统多次调用 startService()或  bindService()方法, onCreate() 方法只会在第一次调用时被触发。同理 onDestory () 方法也只会在服务完结时被触发,其原理可看第2.1节该方法的详细说明。

当系统调用Context.bindService()方法时,也会触发Service的onCreate()方法对Service对象的运行条件作初始化处理,然后触发Service 的 onBind ()方法对服务进行绑定,成功获取Service的句柄后,系统就会通过用户自定义的serviceConnection对象onServiceConnected(ComponentName name, IBinder service)方法,对 Service 对象作出处理。最后当系统调用Context.unbindService()结束服务时,就会激发Service的onDestory()方法对运转中的 Service 作最后的处理。

注意系统调用 Context.bindService()方法,完成 Service.onBind() 绑定后就会触发 serviceConnection对象的 onServiceConnected()方法,但只要系统未使用 Context.unbindService()方法对 service 服务进行解绑,即使多次调用 bindService(),系统也只会在第一次绑定时调用 onBind() 和 onServiceConnected方()法一次。这正是 startService()与 bindService()方法其中的区别,单从字面上理解 startService () 启动服务是可以多次执行,所以多次调用 startService()方法都会触发 onStartCommand()事件,而 bindService() 是绑定服务,所以只要服务已经被绑定,在未解绑时也不会多次执行onServiceConnected()绑定后的操作,这也是两者在使用场景上的区别所在。

Service 生命周期   图2.2

Service 的运转流程就先介绍到这里,具体的使用方法将在下面的章节中详细介绍。

回到目录

三、Local Service 应用原理与开发实例

3.1 通过 Context.startService 启动 Service 服务

首先建立MyService继承Service,实现onCreate()、onDestory()、onStartCommand()、onStart()等几个方法,使用日志记录其运作信息。在Activity中通过Intent绑定Service服务,通过Context.startService()启动服务,通过Context.stopService()结束服务。

 1 public class MainActivity extends Activity {
 2 
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7     }
 8     
 9     public void btnStart_onclick(View view){    
10         //通过Intent绑定MyService,加入输入参数    
11         Intent intent=new Intent(MainActivity.this,MyService.class);
12         intent.putExtra("Name", "Leslie");
13         Log.i(Context.ACTIVITY_SERVICE, "----------onClick startService-----------");
14         //启动MyService
15         startService(intent);
16     }
17     
18     public void btnStop_onclick(View view){
19         Intent intent=new Intent(MainActivity.this,MyService.class);
20         Log.i(Context.ACTIVITY_SERVICE, "----------onClick stopService------------");
21         //停止MyService
22         stopService(intent);
23     }
24 }
25 
26 public class MyService extends Service{
27 
28     @Override
29     public void onCreate(){
30         Log.i(Context.ACTIVITY_SERVICE,"Service onCreate");
31         super.onCreate();
33     }
34     
35     @Override
36     public void onDestroy() {
37         Log.i(Context.ACTIVITY_SERVICE, "Service onDestroy");
38         super.onDestroy();
39     }
40     
41     @Override
42     public void onStart(Intent intent, int startId){
43         Log.i(Context.ACTIVITY_SERVICE,"Service onStart");
44         super.onStart(intent, startId);
45     }
46     
47     @Override
48     public int onStartCommand(Intent intent, int flags, int startId) {
49         Log.i(Context.ACTIVITY_SERVICE, "Service onStartCommand");
50         String name=intent.getStringExtra("Name");
51         Log.i(Context.ACTIVITY_SERVICE,"His name is "+name);
52         return super.onStartCommand(intent, flags, startId);
53     }
54 }

AndroidManifest.xml 文件绑定

 1         <activity
 2             android:name=".MainActivity"
 3             android:label="@string/title_activity_main" >
 4             <intent-filter>
 5                 <action android:name="android.intent.action.MAIN" />
 6                 <category android:name="android.intent.category.LAUNCHER" />
 7             </intent-filter>
 8         </activity>
 9         <service
10             android:name="android.services.MyService"
11             android:enabled="true">
12         </service>

Service 配置说明:

  • android:name       服务类名,注意如果Service与Activity不在同一个包中,在android:name上必须写上Service的全路径
  • android:label      服务的名字,如果为空,默认显示的服务名为类名
  • android:icon       服务的图标
  • android:permission 申明此服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务
  • android:process    表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字
  • android:enabled   如果此项设置为 true,那么 Service 将会默认被系统启动,默认值为 false
  • android:exported 表示该服务是否能够被其他应用程序所控制或连接,默认值为 false

查看处理结果可清楚看到,多次调用startService()后,使用stopService()结束Service服务,onCreate()、onDestory()只会在Service启动和结束时被调用一次。只有Service中的onStartCommand()方法会被多次调用。而Android 2.0以下旧版的方法onStart()会在onStartCommand()调用过程中被激发。

 

3.2 通过Context.bindService启动Service服务

在介绍Context.bindService()前,先讲解一下与此相关的常用类 Binder、ServiceConnection,首先 IBinder 是 Binder 远程对象的基本接口,是为高性能而设计的轻量级远程调用机制的核心部分。这个接口定义了与远程对象交互的协议,但它不仅用于远程调用,也用于进程内调用。系统可以通过它以获取Service的句柄,在此先简单介绍它的基本用法,在下面关于Remote Service远程服务对象时再详细讲述IBinder的主体功能。ServiceConnection主要用于通过Binder绑定Service句柄后,对Service对象进行处理,它主要有两个方法void onServiceConnected(ComponentName name, IBinder service)和void onServiceDisconnected(ComponentName name)。在Context.bindService()完成绑定后,系统就会调用 onServiceConnected() 方法,用户可以通过 IBinder 参数获取Service句柄,对Service进行处理。而 onServiceDisconnected() 方法一般不会被调用,只有Service被绑定后,由于内存不足等问题被意外 kill 时才会被调用。下面举个例子说明一下bindService()的用法。

 1 public class MainActivity extends Activity {
 2     private MyServiceConnection serviceConnection;
 3     
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.activity_main);
 8         
 9         serviceConnection=new MyServiceConnection();
10     }
11     
12     public void btnBind_onclick(View view){
13         //绑定 MyService        
14         Intent intent=new Intent(this,MyService.class);
15 
16         Log.i(Context.ACTIVITY_SERVICE, "----------onClick bindService-----------");
17         //通过bindService(intent,serviceConnection,int)方式启动Service
18         bindService(intent,this.serviceConnection,Context.BIND_AUTO_CREATE);
19     }
20     
21     public void btnUnbind_onclick(View view){
22         Log.i(Context.ACTIVITY_SERVICE, "----------onClick unbindService----------");
23         unbindService(serviceConnection);
24     }
25 }
26 
27 public class MyService extends Service{
28     private MyBinder myBinder;
29 
30     @Override
31     public IBinder onBind(Intent intent) {
32         Log.i(Context.ACTIVITY_SERVICE,"Service onBind");
33         return this.myBinder;
34     }
35     
36     @Override
37     public boolean onUnbind(Intent intent){
38         Log.i(Context.ACTIVITY_SERVICE,"Service onUnbind");
39         return super.onUnbind(intent);
40     }
41     
42     @Override
43     public void onCreate(){
44         super.onCreate();
45         Log.i(Context.ACTIVITY_SERVICE,"Service onCreate");
46         myBinder=new MyBinder();
47     }
48     
49     @Override
50     public void onDestroy() {
51         Log.i(Context.ACTIVITY_SERVICE, "Service onDestroy");
52         super.onDestroy();
53     }
54     
55     public String getDate(){
56         Calendar calendar = Calendar.getInstance();
57         return calendar.getTime().toString();
58     }
59     
60     public class MyBinder extends Binder {
61         public MyService getService(){
62             return MyService.this;
63         }      
64     }
65 }
66 
67 public class MyServiceConnection implements ServiceConnection{
68  
69     @Override
70     public void onServiceConnected(ComponentName name, IBinder service){
71         Log.i(Context.ACTIVITY_SERVICE, "Service Connected");
72         String data=null;
73         //通过IBinder获取Service句柄 
74         MyService.MyBinder myBinder=(MyService.MyBinder)service;    
75         MyService myService=myBinder.getService();
76         data=myService.getDate();
77         
78         Log.i(Context.ACTIVITY_SERVICE,data);
79     }
80     
81     @Override
82     public void onServiceDisconnected(ComponentName name) {
83         Log.i(Context.ACTIVITY_SERVICE, "Service Disconnected");
84     }
85 }

在运行时多次点击按钮激发btnBind_onclick(View view)方法后再使用btnUnbind_onclick(View view)结束服务,请留意处理结果。当系统调用Context .bindService()后,Service将跟随onCreate()、onBind()、onUnbind()、onDestory()的流程走下去。在成功完成onBind()绑定后,就会激发ServiceConnection对象的onServiceConnected()方法,在此用户可对Service进行处理。记得第2.2节所提过的问题,即使多次调用Context.bindService()方法,只要没有调用unbindService()结束绑定,系统只会在第一次调用时激发Service.onBind()和onServiceConnected()方法,这点从运行结果中可得到证实。

注意:调用 Context .bindService() 启动 Service 后 ,只能调用 unbindService() 一次,如重复多次调用此方法系统将会抛出错误异常。所以最简单的处理方式是设置一个静态变量 boolean connected,在调用 unbindService() 前先作出判断

 1 public class MainActivity extends Activity {
 2     private MyServiceConnection serviceConnection;
 3     private static boolean connected;
 4 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         
10         serviceConnection=new MyServiceConnection();
11     }
12     
13     public void btnBind_onclick(View view){
14         connected=true;
15         //绑定 MyService        
16         Intent intent=new Intent(this,MyService.class);
17 
18         Log.i(Context.ACTIVITY_SERVICE, "----------onClick bindService-----------");
19         //通过bindService(intent,serviceConnection,int)方式启动Service
20         bindService(intent,this.serviceConnection,Context.BIND_AUTO_CREATE);
21     }
22     
23     public void btnUnbind_onclick(View view){
24         Log.i(Context.ACTIVITY_SERVICE, "----------onClick unbindService----------");
25         if(connected){
26             unbindService(serviceConnection);
27             connected=false;
28         }
29     }
30 }

 

3.3 Service 服务的综合运用

在前两节只是从初级阶段介绍了Service服务的使用原理,无论是使用startService()或者bindService()启动服务,Service服务的运行都是阶段性,当使用stopService()、unbindService()后,Service服务就会结束。然而从现实应用层面上看,Service 服务很多时候是长驻后台的,它会记录程序运行的流程,当今的状态等重要信息。此时,更多的使用方式就是结合startService()、bindService()两种方式调用Service服务,startService()负责管理Service服务的启动,输入初始化参数,bindService()负责定时对Service服务进行检测。而且流程是有规律性,以startService()启动服务后,每使用bindService()绑定服务,就通过serviceConnection对服务进行检测,然后以unbindService()结束绑定。注意,此时服务并未结束,而是长期运行于后台,直到系统以stopService()方法结束服务后,Service才会最终完结。

  1 public class MainActivity extends Activity {
  2     private MyServiceConnection serviceConnection;
  3     
  4     @Override
  5     protected void onCreate(Bundle savedInstanceState) {
  6         super.onCreate(savedInstanceState);
  7         setContentView(R.layout.activity_main);
  8         
  9         serviceConnection=new MyServiceConnection();
 10     }
 11     
 12     public void btnBind_onclick(View view){
 13         //绑定 MyService        
 14         Intent intent=new Intent(this,MyService.class);
 15 
 16         Log.i(Context.ACTIVITY_SERVICE, "----------onClick bindService-----------");
 17         //通过bindService(intent,serviceConnection,int)方式启动Service
 18         bindService(intent,this.serviceConnection,Context.BIND_AUTO_CREATE);
 19     }
 20     
 21     public void btnUnbind_onclick(View view){
 22         Log.i(Context.ACTIVITY_SERVICE, "----------onClick unbindService----------");
 23         unbindService(serviceConnection);
 24     }
 25     
 26     public void btnStart_onclick(View view){    
 27         //通过Intent绑定MyService,加入初始参数    
 28         Intent intent=new Intent(MainActivity.this,MyService.class);
 29         intent.putExtra("param",0.88);
 30         Log.i(Context.ACTIVITY_SERVICE, "----------onClick startService-----------");
 31         //启动MyService
 32         startService(intent);
 33     }
 34     
 35     public void btnStop_onclick(View view){
 36         Intent intent=new Intent(MainActivity.this,MyService.class);
 37         Log.i(Context.ACTIVITY_SERVICE, "----------onClick stopService------------");
 38         //停止MyService
 39         stopService(intent);
 40     }
 41 }
 42 
 43 public class MyService extends Service{
 44     private MyBinder myBinder;
 45     private double param;
 46 
 47     @Override
 48     public void onStart(Intent intent, int startId){
 49         Log.i(Context.ACTIVITY_SERVICE,"Service onStart");
 50         super.onStart(intent, startId);
 51     }
 52     
 53     @Override
 54     public int onStartCommand(Intent intent, int flags, int startId) {
 55         Log.i(Context.ACTIVITY_SERVICE, "Service onStartCommand");
 56         //获取Context.startService设置的param初始值
 57         this.param=intent.getDoubleExtra("param",1.0);
 58         return super.onStartCommand(intent, flags, startId);
 59     }
 60 
 61     @Override
 62     public IBinder onBind(Intent intent) {
 63         Log.i(Context.ACTIVITY_SERVICE,"Service onBind");
 64         return this.myBinder;
 65     }
 66     
 67     @Override
 68     public boolean onUnbind(Intent intent){
 69         Log.i(Context.ACTIVITY_SERVICE,"Service onUnbind");
 70         return super.onUnbind(intent);
 71     }
 72     
 73     @Override
 74     public void onCreate(){
 75         super.onCreate();
 76         Log.i(Context.ACTIVITY_SERVICE,"Service onCreate");
 77         myBinder=new MyBinder();
 78     }
 79     
 80     @Override
 81     public void onDestroy() {
 82         Log.i(Context.ACTIVITY_SERVICE, "Service onDestroy");
 83         super.onDestroy();
 84     }
 85     
 86     //获取处理后的值
 87     public double getValue(int value){
 88         return value*param;
 89     }
 90     
 91     public class MyBinder extends Binder {
 92         public MyService getService(){
 93             return MyService.this;
 94         }      
 95     }
 96 }
 97 
 98 public class MyServiceConnection implements ServiceConnection{
 99  
100     @Override
101     public void onServiceConnected(ComponentName name, IBinder service){
102         Log.i(Context.ACTIVITY_SERVICE, "Service Connected");
103         //通过IBinder获取Service句柄 
104         MyService.MyBinder myBinder=(MyService.MyBinder)service;    
105         MyService myService=myBinder.getService();
106         //生成随机数输入
107         Random random=new Random();
108         double value=myService.getValue(random.nextInt(10)*1000);
109 //显示计算结果 110 Log.i(Context.ACTIVITY_SERVICE,String.valueOf(value)); 111 } 112 113 @Override 114 public void onServiceDisconnected(ComponentName name) { 115 Log.i(Context.ACTIVITY_SERVICE, "Service Disconnected"); 116 } 117 }

通过startService() 启动服务后,多次使用bindService()绑定服务,unbindService()解除绑定,最后通过stopService()结束服务后,可以看到下面的结果
这时候 Service 的onBind()方法和onUnbind()方法只在第一个bindService流程中触发,其后多次调用bindService(),此事件都不会被触发,而只会触发onServiceConnected()事件。这是因为在默认情况下,系统在绑定时会先搜索IBinder接口,如果Service已经绑定了Binder对象,系统就会直接跳过onBind()方法。

 

既然 onBind(),onUnbind()方法只会在第一次启动绑定时被调用,如果在多次绑定时需要有不同的处理方式又该如何,还好Android为大家预备了一个备用方法void onRebind(intent),Service服务中 boolean onUnbind(intent)的默认返回值为false,只要将此方法的返回值修改为true,则系统在第二次调用Context.bindService()开始,就会激活Service.onRebind(intent)方法。在此对上面的方法作出少量修改,就会看到下面的处理结果。

 1 public class MyService extends Service{
 2     ...........
 3     @Override
 4     public void onRebind(Intent intent){
 5         Log.i(Context.ACTIVITY_SERVICE,"Service onRebind");
 6         super.onRebind(intent);
 7     }
 8     
 9     @Override
10     public boolean onUnbind(Intent intent){
11         Log.i(Context.ACTIVITY_SERVICE,"Service onUnbind");
12         //将返回值设置为true
13         return true;
14     }
15     ...........
16     ...........
17 }

运行结果

注意:此使用方法只适用 startService()、bindServcie()同时被调用的情况下,如果只调用其中一个方法,无论onUnbind()返回值为何值都无法触发onRebind()方法

回到目录

四、通过多线程方式处理 Service 的延时性操作 

4.1 以 Runnable接口实现 Service 多线程操作

由于Android 系统的资源有限,而且对屏幕显示,事件发应,用户体现都有较高的要求,所以在CPU、RAM、GPU、GPU都有独立的运行机制。当主线程中存在大文件读取、图片批量处理、网络连接超时等操作时,一旦时间超过5秒,Android 系统就会出现 “设置运行缓慢” 的提示,Logcat日志上也会显示 “The application may be doing too much work on its main thread” 等提示。在开发Service服务时,若存在此类操作时,开发人员就应该尝试使用多线程方式进行开发,避免主线程被长时间占用。下文将以简单的 Runnable 接口方式实现多线程作为例子。

 1 public class MainActivity extends Activity {
 2     
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7     }
 8     
 9     public void btnStart_onclick(View view){        
10         Intent intent=new Intent(MainActivity.this,MyService.class);
11         Log.i(Context.ACTIVITY_SERVICE, "----------onClick startService-----------------");
12         startService(intent);
13     }
14     
15     public void btnStop_onclick(View view){
16         Intent intent=new Intent(MainActivity.this,MyService.class);
17         Log.i(Context.ACTIVITY_SERVICE, "----------onClick stopService------------------");
18         stopService(intent);
19     }
20 }
21 
22 public class MyService extends Service{
23     
24     @Override
25     public void onCreate(){
26         Log.i(Context.ACTIVITY_SERVICE,"Service onCreate");
27         super.onCreate();
28     }
29 
30     @Override
31     public int onStartCommand(Intent intent, int flags, int startId) {
32         Log.i(Context.ACTIVITY_SERVICE, "Service onStartCommand");
33         Log.i(Context.ACTIVITY_SERVICE,"Main thread id is "+Thread.currentThread().getId());
34         //以异步方式进行模拟操作
35         Thread background=new Thread(new AsyncRunnable());
36         background.start();
37         return super.onStartCommand(intent, flags, startId);
38     }
39     
40     @Override
41     public void onDestroy() {
42         Log.i(Context.ACTIVITY_SERVICE, "Service onDestroy");
43         super.onDestroy();
44     }
45 }
46 
47 public class AsyncRunnable implements Runnable {
48 
49     @Override
50     public void run() {
51         try {
52             Log.i(Context.ACTIVITY_SERVICE,"Async thread id is "+Thread.currentThread().getId());
53             //虚拟操作
54             for(int n=0;n<8;n++){
55                Thread.sleep(1000);
56                Log.i(Context.ACTIVITY_SERVICE,"****Do Work****");
57             }
58         } catch (InterruptedException e) {
59             // TODO 自动生成的 catch 块
60             e.printStackTrace();
61         }
62     }
63 }

请留意运行结果,主线程与onStartCommand()方法内部操作存在于不同的线程当中完成

 

4.2 IntentService 服务简介

在Service服务中出现延时性操作是普遍遇到的情况,有见及此 Android 系统早为开发人员提供了一个Service的子类IntentService,当IntentService执行 startService()方法时,系统将使用一个循环程序将该服务加入到一个子线程队列当中,以便执行服务当中的操作。下面为大家提供 IntentService的源代码,让各位更好的理解IntentService的运行方式。

 1 public abstract class IntentService extends Service {
 2     private volatile Looper mServiceLooper;
 3     private volatile ServiceHandler mServiceHandler;
 4     private String mName;
 5     private boolean mRedelivery;
 6 
 7     private final class ServiceHandler extends Handler {
 8         public ServiceHandler(Looper looper) {
 9             super(looper);
10         }
11 
12         @Override
13         public void handleMessage(Message msg) {
14             onHandleIntent((Intent)msg.obj);
15             stopSelf(msg.arg1);
16         }
17     }
18 
19     public IntentService(String name) {
20         super();
21         mName = name;
22     }
23 
24     public void setIntentRedelivery(boolean enabled) {
25         mRedelivery = enabled;
26     }
27 
28     @Override
29     public void onCreate() {
30         super.onCreate();
31         HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
32         thread.start();
33 
34         mServiceLooper = thread.getLooper();
35         mServiceHandler = new ServiceHandler(mServiceLooper);
36     }
37 
38     @Override
39     public void onStart(Intent intent, int startId) {
40         Message msg = mServiceHandler.obtainMessage();
41         msg.arg1 = startId;
42         msg.obj = intent;
43         mServiceHandler.sendMessage(msg);
44     }
45 
46     @Override
47     public int onStartCommand(Intent intent, int flags, int startId) {
48         onStart(intent, startId);
49         return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
50     }
51 
52     @Override
53     public void onDestroy() {
54         mServiceLooper.quit();
55     }
56 
57     @Override
58     public IBinder onBind(Intent intent) {
59         return null;
60     }
61 
62     protected abstract void onHandleIntent(Intent intent);
63 }

从代码中可以看到,系统没有在onStartCommand()中创建新线程,而是在onCreate()方法中建立了独立的工作线程,这是由于onCreate()方法只会在新建服务时被调用一次,可见这样的目的是为了让系统在单个线程中执行多个异步任务。当系统调用Context.startService()方法时,系统将通过onStart()方法使用异步方式,调用ServiceHandler.handleMessage(msg)进行处理,而handleMessage(msg)正是调用了虚拟方法onHandleIntent(intent),然后以stopSelf()结束服务。所以用户只需要在继承类中重写onHandleIntent(intent)方法,便可以以异步方法执行IntentService。

 

4.3 IntentService 应用

以下面一个简单的例子说明一下IntentService的应用,建立一个MyIntentService类继承IntentService,实现onHandleIntent(Message msg)方法。然后在MainActivity活动分别3次以不同参数调用intentService,观察其运行的线程状态。

 1 public class MyIntentService extends IntentService {
 2     
 3     public MyIntentService() {
 4         super(null);
 5     }
 6 
 7     @Override
 8     protected void onHandleIntent(Intent intent) {
 9         String msg=intent.getStringExtra("msg");
10         Log.i(Context.ACTIVITY_SERVICE,msg+"'s thread id is "+Thread.currentThread().getId());
11     }
12 }
13 
14 public class MainActivity extends Activity {
15 
16     @Override
17     protected void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.activity_main);
20     }
21     
22     public void btnStart_onclick(View view){    
23         Log.i(Context.ACTIVITY_SERVICE, "----------onClick startService--------------");
24         Log.i(Context.ACTIVITY_SERVICE,"Main thread id is "+Thread.currentThread().getId());
25         
26         Intent intent1=new Intent(this,MyIntentService.class);
27         intent1.putExtra("msg", "intentService1");
28         startService(intent1);
29         
30         Intent intent2=new Intent(this,MyIntentService.class);
31         intent2.putExtra("msg", "intentService2");
32         startService(intent2);
33         
34         Intent intent3=new Intent(this,MyIntentService.class);
35         intent3.putExtra("msg", "intentService3");
36         startService(intent3);
37     }
38     
39     public void btnStop_onclick(View view){
40         Intent intent=new Intent(MainActivity.this,MyIntentService.class);
41         Log.i(Context.ACTIVITY_SERVICE, "----------onClick stopService-------------");
42         stopService(intent);
43     }
44 }

在AndroidManifest.xml 文件设置服务

1    <application>
2         ..........
3         <service
4             android:name="android.services.MyIntentService"
5             android:enabled="true">
6         </service>
7     </application>

从运行结果中可以看出,同一时间多次启动startService()调用intentService,它们都将运行于同一个异步线程当中,这一点在这里得到了证实。

回到目录

 

五、浅谈 Remote Service 原理

5.1 跨进程通信的使用场景

以上章节所举的例子都是使用Local Service 技术,Serivce服务端与Client客户端都是在于同一进程当中,当APP被卸御,Service服务也被同时卸御。要是想把服务端与客户端分别放在不同的进程当中进行跨进程信息交换的话,就需要使用到下面介绍的远程通信服务 Remote Service。使用Remote Service可以把服务端与客户端分离,当一方被卸御,另一方不会被影响。当今有很多企业都有多个独立的APP,如阿里巴巴旗下就天猫、淘宝、聚划算、支付宝等多个APP,这时候就有需要把Service服务放在一独立的后台进程当中,作为多个APP之间信息交换的桥梁。这样如用户信息,用户登录,身份验证等多个共用的模块都可以在Service服务中实现,以供不同的APP进行调用。而且当APP被关闭时,Service服务还会寄存在后台当中,对用户的操作进行检测。如今越来越多的企业都使用这种开发方式,以收集用户像所在地点,通信录,短信,彩信等个人信息,方便企业针对用户的个人资料进行产品推广。

5.2 Remote Service 技术背景

Android 系统与 Windows 系统的通信原则基本一致,进程就是安全策略的边界,不同的APP属于不同进程 Process,一个进程不能直接访问其他进程的资源。需要实现多进程间的通信,就要使用IPC(Inter Process Commnication)进程间通信技术。Android 系统的 IPC 机制是基于 RPC (Remote Proceduce Call) 远程过程调用协议建立的,与 Java 使用的 RMI(Rmote Methed Invocation)远程方法调用相比,不同之处在于Android的IPC机制是基于AIDL(Android Interface Definition Language)接口定义语言定制进程间的通讯规则的。系统会基于 AIDL 规则把信息进行序列化处理,然后发送到另一个进程当中,Android 系统把这种基于跨进程通信的服务称作 Remote Service 。

5.3 IPC 运作原理

从底层架构分析, Android 系统中 IPC 的运作主要依赖于 “ServiceManager” 和 “Binder Driver” 两个核心元件,下面给大家简单介绍一下它们的运作原理:

  • ServiceManager 简介

ServiceManager是Android系统内的服务管理器,主要负责管理 Service 服务的管理,注册,调用等任务。在Google提供的Android原始代码中可以找到(文件夹路径:frameworks/base/cmds/servicemanager),有C语言开发基础且有兴趣的朋友可以下载看一下,当中包含了几个核心的函数:

int svcmgr_handler(struct binder_state *bs, struct binder_txn *txn, struct binder_io *msg, struct binder_io *reply)
int do_add_service(struct binder_state *bs, uint16_t *s, unsigned len, void *ptr, unsigned uid)
void *do_find_service(struct binder_state *bs, uint16_t *s, unsigned len)
void binder_loop(struct binder_state *bs, binder_handler func)

ServiceManager 启动后会通过 binder_loop 循环对 Binder Driver 进行监听,当发现了有新的Service服务请求后,就会调用 svcmgr_handler() 函数对检测的Service服务进行处理,通过*do_find_service()函数可以在svclist集中检测Service服务,若当前svclist服务集中未存在当前服务,就会通过do_add_service()进行注册,把当前服务及其唯一标识符加入到svclist中,这样当前的 Service 服务被绑定后就完成在ServiceManager的注册。Binder Driver 会按照规定的格式把它转化为 Binder 实体发送到内核当中,当被 Client 调用时 ServiceManager 会根据 Service 服务的标识符在 svclist 中找到该 Binder 实体,并把 Binder 实体的引用发送给Client。完成计算后 Binder Driver 会进行数据处理,把计算结果发回到Client客户端。由于Binder实体是以强类型的形式存在,所以即使被多次引用,系统都会指向同一个Binder实体,除非所有都结束链接,否则Binder实体会一直存在。

图 5.3

  • Binder Driver简介

Binder Driver运行于Android 内核当中,它以 “字符驱动设备” 中的 “misc设备注册” 存在于设备目录 dev/binder,由于权限问题,在一般手机中没有权限进行复制,对此有兴趣的朋友可以在google 提供的 android 源代码中查看。它提供open(),mmap(),poll(),ioctl() 等函数进行标准化文件操作,负责进程之间Binder通信的建立,Binder实体在进程之间的传递,Binder实体引用的计数管理,数据包在进程之间的传递与交互等一系列底层操作。

5.4 Remote Service 常用接口

在 5.3 节以 Android 底层结构的方式简单介绍了一下 IPC 通信的原理,下面将以 JAVA 应用层方式再作介绍。

  • IBinder 接口

IBinder 是 Remote Service 远程服务的常用接口,Binder是它的实现类,它是为高性能而设计的轻量级远程调用机制的核心部分。IBinder 内部比较重要的方法就是 boolean transact(int code, Parcel data, Parcel reply, int flags) ,它负责在服务器与客户端之间进行信息交换,调用远程方法进行处理,然后把返回值转换成可序列化对象送回客户端。

5.5 Remote Service 开发实例

首先新建一个项目作为服务端, 建立 AIDL 文件 ITimerService.aidl,系统会根据接口描述自动在gen文件夹内生成对应的类文件 ITimerService.java ,当中 Stub 扩展了 android.os.Binder 并利用 transact ()实现了 ITimerService 接口中方法的远程调用。

1 package com.example.remoteservice;
2 
3 interface ITimerService{
4     String getTimeNow();
5 }

gen\com\example\remoteservice\ITimerService.java (自动生成)

 1 package com.example.remoteservice;
 2 public interface ITimerService extends android.os.IInterface
 3 {
 4 /** Local-side IPC implementation stub class. */
 5 public static abstract class Stub extends android.os.Binder implements com.example.remoteservice.ITimerService
 6 {
 7 private static final java.lang.String DESCRIPTOR = "com.example.remoteservice.ITimerService";
 8 /** Construct the stub at attach it to the interface. */
 9 public Stub()
10 {
11 this.attachInterface(this, DESCRIPTOR);
12 }
13 /**
14  * Cast an IBinder object into an com.example.remoteservice.ITimerService interface,
15  * generating a proxy if needed.
16  */
17 public static com.example.remoteservice.ITimerService asInterface(android.os.IBinder obj)
18 {
19 if ((obj==null)) {
20 return null;
21 }
22 android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
23 if (((iin!=null)&&(iin instanceof com.example.remoteservice.ITimerService))) {
24 return ((com.example.remoteservice.ITimerService)iin);
25 }
26 return new com.example.remoteservice.ITimerService.Stub.Proxy(obj);
27 }
28 @Override public android.os.IBinder asBinder()
29 {
30 return this;
31 }
32 @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
33 {
34 switch (code)
35 {
36 case INTERFACE_TRANSACTION:
37 {
38 reply.writeString(DESCRIPTOR);
39 return true;
40 }
41 case TRANSACTION_getTimeNow:
42 {
43 data.enforceInterface(DESCRIPTOR);
44 java.lang.String _result = this.getTimeNow();
45 reply.writeNoException();
46 reply.writeString(_result);
47 return true;
48 }
49 }
50 return super.onTransact(code, data, reply, flags);
51 }
52 private static class Proxy implements com.example.remoteservice.ITimerService
53 {
54 private android.os.IBinder mRemote;
55 Proxy(android.os.IBinder remote)
56 {
57 mRemote = remote;
58 }
59 @Override public android.os.IBinder asBinder()
60 {
61 return mRemote;
62 }
63 public java.lang.String getInterfaceDescriptor()
64 {
65 return DESCRIPTOR;
66 }
67 @Override public java.lang.String getTimeNow() throws android.os.RemoteException
68 {
69 android.os.Parcel _data = android.os.Parcel.obtain();
70 android.os.Parcel _reply = android.os.Parcel.obtain();
71 java.lang.String _result;
72 try {
73 _data.writeInterfaceToken(DESCRIPTOR);
74 mRemote.transact(Stub.TRANSACTION_getTimeNow, _data, _reply, 0);
75 _reply.readException();
76 _result = _reply.readString();
77 }
78 finally {
79 _reply.recycle();
80 _data.recycle();
81 }
82 return _result;
83 }
84 }
85 static final int TRANSACTION_getTimeNow = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
86 }
87 public java.lang.String getTimeNow() throws android.os.RemoteException;
88 }

然后建立服务TimerService,建立内置类TimerServiceImpl实现接口ITimerService中的方法,由于使用 Remote Service 只能使用 bindService()方式对服务进行远程绑定,所以TimerService中须利用 onBind() 方法绑定 TimerServiceImpl 对象。

 1 public class TimerService extends Service {
 2 
 3     @Override
 4     public IBinder onBind(Intent intent) {
 5         // TODO 自动生成的方法存根
 6         return new TimerServiceImpl();
 7     }
 8 
 9     public class TimerServiceImpl extends ITimerService.Stub{
10 
11         @Override
12         public String getTimeNow() throws RemoteException {
13             // 获取当时时间与服务器端的进程Id
14             Date date=new Date();
15             SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
16             return  "Time now is "+ formatter.format(date)+"\nService processId is "+Process.myPid();
17         }
18     }
19 }

在 AndroidManifest.xml 文件设置服务绑定,在 action 项的 android:name 中绑定当前服务的接口

1     <application>
2         ........
3         <service android:name=".TimerService" android:process=":remote">
4             <intent-filter>
5                 <action android:name="com.example.remoteservice.ITimerService"/>
6             </intent-filter>
7         </service>
8     </application>

服务器端完成配置后建立一个客户端项目,把ITimerService.aidl文件copy到客户端,此时客户端也会在gen文件夹中自动生成ITimerService.java文件。在Activity中调用Remote Service时请注意,android 4.0 及以下版本,可通过 Intent(string action) 构造函数生成后直接调用。android 5.0 及以上版本需通过intent.setPackage(string packageName)指定action的包名称。

 1 public class MainActivity extends Activity {
 2     private MyServiceConnection serviceConnection;
 3     private boolean connected;
 4     
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         //建立ServiceConnection对象
10         serviceConnection=new MyServiceConnection();
11     }
12     
13     public void btnBind_onclick(View view){        
14         Intent intent=new Intent();
15         //绑定远程服务接口
16         intent.setAction("com.example.remoteservice.ITimerService");
17         intent.setPackage("com.example.remoteservice");
18         this.connected=true;
19         Log.i(Context.ACTIVITY_SERVICE, "-------onClick bindService--------");
20         bindService(intent,this.serviceConnection,Context.BIND_AUTO_CREATE);    
21     }
22     
23     public void btnUnbind_onclick(View view){
24         Log.i(Context.ACTIVITY_SERVICE, "-------onClick unbindService---------");
25         if(connected){
26            unbindService(serviceConnection);
27            connected=false;
28         }
29     }
30 }
31 
32 public class MyServiceConnection implements ServiceConnection{
33 
34     @Override
35     public void onServiceConnected(ComponentName name, IBinder service){
36         // TODO 自动生成的方法存根
37         Log.i(Context.ACTIVITY_SERVICE, "Service Connected");
38         //获取远程对象
39         ITimerService timerService=ITimerService.Stub.asInterface(service);    
40         String data=null;
41         
42         try {
43             data=timerService.getTimeNow()+"\nClient processId is "+Process.myPid();
44         } catch (RemoteException e) {
45             // TODO 自动生成的 catch 块
46             e.printStackTrace();
47         }
48 
49         Log.i(Context.ACTIVITY_SERVICE,data);
50     }
51 }   

从运行结果可清晰看到Service与Client运行于不同的进程当中

 

5.6 Remote Service 复杂类型数据传输

当 Remote Service 需要使用自定义类型的数据进行传输时,数据对象需要经过序列化处理,而 Android 对象的序列化处理有两种方式,一是常用方式 Serializable 接口,另一个是 Android 独有的Parcelable 接口。由于常用的 Serializable 接口,会使用大量的临时变量耗费内存而导致大量的GC垃圾回收,引起手机资源不足,因此 Android 研发出 Parcelable 接口实现对象的序列化。它可被看作为一个 Parcel 容器,通过 writeToParcel() 与 createFormParcel() 方法把对象读写到 Parcel 当中,Parcelable接口如下:

 1 public interface Parcelable 
 2 {
 3     //内容描述接口
 4     public int describeContents();
 5     //对象序列化方式
 6     public void writeToParcel(Parcel dest, int flags);
 7     
 8     //反序列化对象,使用泛型方式在Parcel中构造一个实现了Parcelable的类的实例处理。
 9     //接口分别定义了单个实例和多个实例
10     public interface Creator<T> 
11     {
12         public T createFromParcel(Parcel source);
13         public T[] newArray(int size);
14     }
15 }

首先建立服务端,新建Person.aidl文件

1 package com.example.remoteservice;
2 
3 parcelable Person;  

建立Person类,实现Parcelable接口

 1 public class Person implements Parcelable {
 2    private String name;
 3    private Integer age;
 4    private String desc;
 5    
 6    public Person(){
 7    
 8    }
 9    
10    public Person(String name, Integer age, String desc) {
11     // TODO 自动生成的构造函数存根
12        this.name=name;
13        this.age=age;
14        this.desc=desc;
15    }
16 
17    public String getName(){
18        return this.name;
19    }
20    
21    public void setName(String name){
22        this.name=name;
23    }
24    
25    public Integer getAge(){
26        return this.age;
27    }
28    
29    public void setAge(Integer age){
30        this.age=age;
31    }
32    
33    public String getDesc(){
34        return this.desc;
35    }
36    
37    public void setDesc(String desc){
38        this.desc=desc;
39    }
40 
41     @Override
42     public int describeContents() {
43         // TODO 自动生成的方法存根
44         return 0;
45     }
46 
47     @Override
48     public void writeToParcel(Parcel dest, int flags) {
49         // TODO 自动生成的方法存根
50         dest.writeString(name);  
51         dest.writeInt(age);  
52         dest.writeString(desc);  
53     }
54     
55     public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {  
56         
57         /** 
58          * 创建一个要序列号的实体类的数组,数组中存储的都设置为null 
59          */  
60         @Override  
61         public Person[] newArray(int size) {  
62             return new Person[size];  
63         }  
64           
65         /*** 
66          * 根据序列号的Parcel对象,反序列号为原本的实体对象 
67          * 读出顺序要和writeToParcel的写入顺序相同 
68          */  
69         @Override  
70         public Person createFromParcel(Parcel source) {  
71             String name = source.readString();  
72             int age = source.readInt();  
73             String desc = source.readString();  
74             Person Person = new Person();  
75             Person.setName(name);  
76             Person.setAge(age);  
77             Person.setDesc(desc);  
78               
79             return Person;  
80         }  
81     };
82 }

建立服务IPersonService.aidl文件

1 package com.example.remoteservice;
2 
3 import com.example.remoteservice.Person;
4 
5 interface IPersonService{
6     Person getPerson(String number);
7 }

此时在gen\com\example\remoteservice文件夹内将自动生成成IPersonService.java类

  1 /*
  2  * This file is auto-generated.  DO NOT MODIFY.
  3  * Original file: D:\\Java_Projects\\RemoteService\\src\\com\\example\\remoteservice\\IPersonService.aidl
  4  */
  5 package com.example.remoteservice;
  6 public interface IPersonService extends android.os.IInterface
  7 {
  8 /** Local-side IPC implementation stub class. */
  9 public static abstract class Stub extends android.os.Binder implements com.example.remoteservice.IPersonService
 10 {
 11 private static final java.lang.String DESCRIPTOR = "com.example.remoteservice.IPersonService";
 12 /** Construct the stub at attach it to the interface. */
 13 public Stub()
 14 {
 15 this.attachInterface(this, DESCRIPTOR);
 16 }
 17 /**
 18  * Cast an IBinder object into an com.example.remoteservice.IPersonService interface,
 19  * generating a proxy if needed.
 20  */
 21 public static com.example.remoteservice.IPersonService asInterface(android.os.IBinder obj)
 22 {
 23 if ((obj==null)) {
 24 return null;
 25 }
 26 android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
 27 if (((iin!=null)&&(iin instanceof com.example.remoteservice.IPersonService))) {
 28 return ((com.example.remoteservice.IPersonService)iin);
 29 }
 30 return new com.example.remoteservice.IPersonService.Stub.Proxy(obj);
 31 }
 32 @Override public android.os.IBinder asBinder()
 33 {
 34 return this;
 35 }
 36 @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
 37 {
 38 switch (code)
 39 {
 40 case INTERFACE_TRANSACTION:
 41 {
 42 reply.writeString(DESCRIPTOR);
 43 return true;
 44 }
 45 case TRANSACTION_getPerson:
 46 {
 47 data.enforceInterface(DESCRIPTOR);
 48 java.lang.String _arg0;
 49 _arg0 = data.readString();
 50 com.example.remoteservice.Person _result = this.getPerson(_arg0);
 51 reply.writeNoException();
 52 if ((_result!=null)) {
 53 reply.writeInt(1);
 54 _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
 55 }
 56 else {
 57 reply.writeInt(0);
 58 }
 59 return true;
 60 }
 61 }
 62 return super.onTransact(code, data, reply, flags);
 63 }
 64 private static class Proxy implements com.example.remoteservice.IPersonService
 65 {
 66 private android.os.IBinder mRemote;
 67 Proxy(android.os.IBinder remote)
 68 {
 69 mRemote = remote;
 70 }
 71 @Override public android.os.IBinder asBinder()
 72 {
 73 return mRemote;
 74 }
 75 public java.lang.String getInterfaceDescriptor()
 76 {
 77 return DESCRIPTOR;
 78 }
 79 @Override public com.example.remoteservice.Person getPerson(java.lang.String number) throws android.os.RemoteException
 80 {
 81 android.os.Parcel _data = android.os.Parcel.obtain();
 82 android.os.Parcel _reply = android.os.Parcel.obtain();
 83 com.example.remoteservice.Person _result;
 84 try {
 85 _data.writeInterfaceToken(DESCRIPTOR);
 86 _data.writeString(number);
 87 mRemote.transact(Stub.TRANSACTION_getPerson, _data, _reply, 0);
 88 _reply.readException();
 89 if ((0!=_reply.readInt())) {
 90 _result = com.example.remoteservice.Person.CREATOR.createFromParcel(_reply);
 91 }
 92 else {
 93 _result = null;
 94 }
 95 }
 96 finally {
 97 _reply.recycle();
 98 _data.recycle();
 99 }
100 return _result;
101 }
102 }
103 static final int TRANSACTION_getPerson = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
104 }
105 public com.example.remoteservice.Person getPerson(java.lang.String number) throws android.os.RemoteException;
106 }

然后建立服务PersonService,建立内置类PersonServiceImpl实现接口IPersonService中的方法,在 PersonService 中须利用 onBind() 方法绑定 PersonServiceImpl 对象。

 1 public class PersonService extends Service {
 2  
 3     @Override
 4     public IBinder onBind(Intent intent) {
 5         // TODO 自动生成的方法存根
 6         return new PersonServiceImpl();
 7     }
 8 
 9     public class PersonServiceImpl extends IPersonService.Stub{
10         @Override
11         public Person getPerson(String number) throws RemoteException {
12             // TODO 自动生成的方法存根
13             switch(number){
14             case "0":
15                 return new Person("Jack Mokei",34,"Project Manager");
16             case "1":
17                 return new Person("Mike Tlea",24,"Team Leader");
18             default:
19                 return null;
20             }
21         }
22     }
23 }

在 AndroidManifest.xml 文件设置服务绑定,在 action 项的 android:name 中绑定当前服务的接口

1     <application>
2         ........
3         <service android:name=".PersonService" android:process=":remote">
4             <intent-filter>
5                 <action android:name="com.example.remoteservice.IPersonService"/>
6             </intent-filter>
7         </service>
8     </application>

服务器端完成配置后建立一个客户端项目,把Person.aidl、IPersonService.aidl文件copy到客户端,此时客户端也会在gen文件夹中自动生成 Person.java和 IPersonService.java文件

 1 public class MainActivity extends Activity {
 2     private MyServiceConnection serviceConnection;
 3     private boolean connected;
 4     
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         //建立ServiceConnection对象
10         serviceConnection=new MyServiceConnection();
11     }
12     
13     public void btnBind_onclick(View view){        
14         Intent intent=new Intent();
15         //绑定远程服务接口
16         intent.setAction("com.example.remoteservice.IPersonService");
17         intent.setPackage("com.example.remoteservice");
18         this.connected=true;
19         Log.i(Context.ACTIVITY_SERVICE, "----------onClick bindService----------");
20         bindService(intent,this.serviceConnection,Context.BIND_AUTO_CREATE);    
21     }
22     
23     public void btnUnbind_onclick(View view){
24         Log.i(Context.ACTIVITY_SERVICE, "----------onClick unbindService--------");
25         if(connected){
26            unbindService(serviceConnection);
27            connected=false;
28         }
29     }
30 }
31 
32 public class MyServiceConnection implements ServiceConnection{
33 
34     @Override
35     public void onServiceConnected(ComponentName name, IBinder service){
36         Log.i(Context.ACTIVITY_SERVICE, "Service Connected");
37         //绑定远程对象
38         IPersonService personService=IPersonService.Stub.asInterface(service);    
39         String data=null;
40         
41         try {
42             Person person=personService.getPerson("0");
43             data=person.getName()+"'s age is "+person.getAge();
44         } catch (RemoteException e) {
45             // TODO 自动生成的 catch 块
46             e.printStackTrace();
47         }
48 
49         Log.i(Context.ACTIVITY_SERVICE,data);
50     }
51 }

运行结果

 回到目录

 

本章总结

通过文章的例子大家可以了解到Local Service本地服务与Remote Service远程服务之间的区别,以及Context.startService()方法以及Context.bindService()方法不同的使用场景。希望文章有帮于大家对Service服务有更深入的了解,在不同的开发环境中灵活运用。由于时间仓促,文章当中有不明确的地方或有错漏敬请点明。

 

Android开发笔记
 
 
 

作者:风尘浪子

http://www.cnblogs.com/leslies2/p/5401813.html

原创作品,转载时请注明作者及出处

posted on 2016-05-09 11:13  风尘浪子  阅读(11737)  评论(0编辑  收藏  举报

导航