http://blog.youkuaiyun.com/amazing7/article/details/51305911
什么是服务?
Service是一个应用程序组件,它能够在后台执行一些耗时较长的操作,并且不提供用户界面。服务能被其它应用程序的组件启动,即使用户切换到另外的应用时还能保持后台运行。此外,应用程序组件还能与服务绑定,并与服务进行交互,甚至能进行进程间通信(IPC)。 比如,服务可以处理网络传输、音乐播放、执行文件I/O、或者与content provider进行交互,所有这些都是后台进行的。
Service 与 Thread 的区别
服务仅仅是一个组件,即使用户不再与你的应用程序发生交互,它仍然能在后台运行。因此,应该只在需要时才创建一个服务。
如果你需要在主线程之外执行一些工作,但仅当用户与你的应用程序交互时才会用到,那你应该创建一个新的线程而不是创建服务。 比如,如果你需要播放一些音乐,但只是当你的activity在运行时才需要播放,你可以在onCreate()中创建一个线程,在onStart()中开始运行,然后在onStop()中终止运行。还可以考虑使用AsyncTask或HandlerThread来取代传统的Thread类。
由于无法在不同的 Activity 中对同一 Thread 进行控制,这个时候就要考虑用服务实现。如果你使用了服务,它默认就运行于应用程序的主线程中。因此,如果服务执行密集计算或者阻塞操作,你仍然应该在服务中创建一个新的线程来完成(避免ANR)。
服务的分类
按运行分类
-
前台服务
前台服务是指那些经常会被用户关注的服务,因此内存过低时它不会成为被杀的对象。 前台服务必须提供一个状态栏通知,并会置于“正在进行的”(“Ongoing”)组之下。这意味着只有在服务被终止或从前台移除之后,此通知才能被解除。
例如,用服务来播放音乐的播放器就应该运行在前台,因为用户会清楚地知晓它的运行情况。 状态栏通知可能会标明当前播放的歌曲,并允许用户启动一个activity来与播放器进行交互。要把你的服务请求为前台运行,可以调用startForeground()方法。此方法有两个参数:唯一标识通知的整数值、状态栏通知Notification对象。例如:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
要从前台移除服务,请调用stopForeground()方法,这个方法接受个布尔参数,表示是否同时移除状态栏通知。此方法不会终止服务。不过,如果服务在前台运行时被你终止了,那么通知也会同时被移除。
- 后台服务
按使用分类
-
本地服务
用于应用程序内部,实现一些耗时任务,并不占用应用程序比如Activity所属线程,而是单开线程后台执行。
调用Context.startService()启动,调用Context.stopService()结束。在内部可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。 -
远程服务
用于Android系统内部的应用程序之间,可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。可以定义接口并把接口暴露出来,以便其他应用进行操作。客户端建立到服务对象的连接,并通过那个连接来调用服务。调用Context.bindService()方法建立连接,并启动,以调用 Context.unbindService()关闭连接。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加载它。
Service生命周期
Service生命周期方法:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
请注意onStartCommand()方法必须返回一个整数。这个整数是描述系统在杀死服务之后应该如何继续运行。onStartCommand()的返回值必须是以下常量之一:
START_NOT_STICKY
如果系统在onStartCommand()返回后杀死了服务,则不会重建服务了,除非还存在未发送的intent。 当服务不再是必需的,并且应用程序能够简单地重启那些未完成的工作时,这是避免服务运行的最安全的选项。
START_STICKY
如果系统在onStartCommand()返回后杀死了服务,则将重建服务并调用onStartCommand(),但不会再次送入上一个intent, 而是用null intent来调用onStartCommand() 。除非还有启动服务的intent未发送完,那么这些剩下的intent会继续发送。 这适用于媒体播放器(或类似服务),它们不执行命令,但需要一直运行并随时待命。START_REDELIVER_INTENT
如果系统在onStartCommand()返回后杀死了服务,则将重建服务并用上一个已送过的intent调用onStartCommand()。任何未发送完的intent也都会依次送入。这适用于那些需要立即恢复工作的活跃服务,比如下载文件。
服务的生命周期与activity的非常类似。不过,更重要的是你需密切关注服务的创建和销毁环节,因为后台运行的服务是不会引起用户注意的。
服务的生命周期——从创建到销毁——可以有两种路径:
-
一个started服务
这类服务由其它组件调用startService()来创建。然后保持运行,且必须通过调用stopSelf()自行终止。其它组件也可通过调用stopService() 终止这类服务。服务终止后,系统会把它销毁。
如果一个Service被startService 方法多次启动,那么onCreate方法只会调用一次,onStart将会被调用多次(对应调用startService的次数),并且系统只会创建Service的一个实例(因此你应该知道只需要一次stopService调用)。该Service将会一直在后台运行,而不管对应程序的Activity是否在运行,直到被调用stopService,或自身的stopSelf方法。当然如果系统资源不足,android系统也可能结束服务。
-
一个bound服务
服务由其它组件(客户端)调用bindService()来创建。然后客户端通过一个IBinder接口与服务进行通信。客户端可以通过调用unbindService()来关闭联接。多个客户端可以绑定到同一个服务上,当所有的客户端都解除绑定后,系统会销毁服务。(服务不需要自行终止。)
如果一个Service被某个Activity 调用 Context.bindService 方法绑定启动,不管调用 bindService 调用几次,onCreate方法都只会调用一次,同时onStart方法始终不会被调用。当连接建立之后,Service将会一直运行,除非调用Context.unbindService 断开连接或者之前调用bindService 的 Context 不存在了(如Activity被finish的时候),系统将会自动停止Service,对应onDestroy将被调用。
这两条路径并不是完全隔离的。也就是说,你可以绑定到一个已经用startService()启动的服务上。例如,一个后台音乐服务可以通过调用startService()来启动,传入一个指明所需播放音乐的 Intent。 之后,用户也许需要用播放器进行一些控制,或者需要查看当前歌曲的信息,这时一个activity可以通过调用bindService()与此服务绑定。在类似这种情况下,stopService()或stopSelf()不会真的终止服务,除非所有的客户端都解除了绑定。
当在旋转手机屏幕的时候,当手机屏幕在“横”“竖”变换时,此时如果你的 Activity 如果会自动旋转的话,旋转其实是 Activity 的重新创建,因此旋转之前的使用 bindService 建立的连接便会断开(Context 不存在了)。
在manifest中声明服务
无论是什么类型的服务都必须在manifest中申明,格式如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Service 元素的属性有:
android:name ————- 服务类名
android:label ————– 服务的名字,如果此项不设置,那么默认显示的服务名则为类名
android:icon ————– 服务的图标
android:permission ——- 申明此服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务
android:process ———- 表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字
android:enabled ———- 如果此项设置为 true,那么 Service 将会默认被系统启动,不设置默认此项为 false
android:exported ——— 表示该服务是否能够被其他应用程序所控制或连接,不设置默认此项为 false
android:name是唯一必需的属性——它定义了服务的类名。与activity一样,服务可以定义intent过滤器,使得其它组件能用隐式intent来调用服务。如果你想让服务只能内部使用(其它应用程序无法调用),那么就不必(也不应该)提供任何intent过滤器。
此外,如果包含了android:exported属性并且设置为”false”, 就可以确保该服务是你应用程序的私有服务。即使服务提供了intent过滤器,本属性依然生效。
startService 启动服务
从activity或其它应用程序组件中可以启动一个服务,调用startService()并传入一个Intent(指定所需启动的服务)即可。
- 1
- 2
- 1
- 2
服务类:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
一个started服务必须自行管理生命周期。也就是说,系统不会终止或销毁这类服务,除非必须恢复系统内存并且服务返回后一直维持运行。 因此,服务必须通过调用stopSelf()自行终止,或者其它组件可通过调用stopService()来终止它。
bindService 启动服务
当应用程序中的activity或其它组件需要与服务进行交互,或者应用程序的某些功能需要暴露给其它应用程序时,你应该创建一个bound服务,并通过进程间通信(IPC)来完成。
方法如下:
- 1
- 2
- 3
- 1
- 2
- 3
注意bindService是Context中的方法,当没有Context时传入即可。
在进行服务绑定的时,其flags有:
-
Context.BIND_AUTO_CREATE
表示收到绑定请求的时候,如果服务尚未创建,则即刻创建,在系统内存不足需要先摧毁优先级组件来释放内存,且只有驻留该服务的进程成为被摧毁对象时,服务才被摧毁
-
Context.BIND_DEBUG_UNBIND
通常用于调试场景中判断绑定的服务是否正确,但容易引起内存泄漏,因此非调试目的的时候不建议使用
-
Context.BIND_NOT_FOREGROUND
表示系统将阻止驻留该服务的进程具有前台优先级,仅在后台运行。
服务类:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
启动服务的activity代码:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
注意在AndroidMainfest.xml中对Service进行显式声明
判断Service是否正在运行:
实例用法:Service的基本用法
关于Service最基本的用法自然就是如何启动一个Service了,启动Service的方法和启动Activity很类似,都需要借助Intent来实现,下面我们就通过一个具体的例子来看一下。
新建一个Android项目,项目名就叫ServiceTest,这里我选择使用4.0的API。
然后新建一个MyService继承自Service,并重写父类的onCreate()、onStartCommand()和onDestroy()方法,如下所示:
- public class MyService extends Service {
- public static final String TAG = "MyService";
- @Override
- public void onCreate() {
- super.onCreate();
- Log.d(TAG, "onCreate() executed");
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Log.d(TAG, "onStartCommand() executed");
- return super.onStartCommand(intent, flags, startId);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- Log.d(TAG, "onDestroy() executed");
- }
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- }
然后打开或新建activity_main.xml作为程序的主布局文件,代码如下所示:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <Button
- android:id="@+id/start_service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Start Service" />
- <Button
- android:id="@+id/stop_service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Stop Service" />
- </LinearLayout>
然后打开或新建MainActivity作为程序的主Activity,在里面加入启动Service和停止Service的逻辑,代码如下所示:
- public class MainActivity extends Activity implements OnClickListener {
- private Button startService;
- private Button stopService;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- startService = (Button) findViewById(R.id.start_service);
- stopService = (Button) findViewById(R.id.stop_service);
- startService.setOnClickListener(this);
- stopService.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.start_service:
- Intent startIntent = new Intent(this, MyService.class);
- startService(startIntent);
- break;
- case R.id.stop_service:
- Intent stopIntent = new Intent(this, MyService.class);
- stopService(stopIntent);
- break;
- default:
- break;
- }
- }
- }
另外需要注意,项目中的每一个Service都必须在AndroidManifest.xml中注册才行,所以还需要编辑AndroidManifest.xml文件,代码如下所示:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.servicetest"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="14"
- android:targetSdkVersion="17" />
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- ……
- <service android:name="com.example.servicetest.MyService" >
- </service>
- </application>
- </manifest>
也就是说,当启动一个Service的时候,会调用该Service中的onCreate()和onStartCommand()方法。
那么如果我再点击一次Start Service按钮呢?这个时候的打印日志如下:
可以看到,这次只有onStartCommand()方法执行了,onCreate()方法并没有执行,为什么会这样呢?这是由于onCreate()方法只会在Service第一次被创建的时候调用,如果当前Service已经被创建过了,不管怎样调用startService()方法,onCreate()方法都不会再执行。因此你可以再多点击几次Start Service按钮试一次,每次都只会有onStartCommand()方法中的打印日志。
我们还可以到手机的应用程序管理界面来检查一下MyService是不是正在运行,如下图所示:
恩,MyService确实是正在运行的,即使它的内部并没有执行任何的逻辑。
回到ServiceTest程序,然后点击一下Stop Service按钮就可以将MyService停止掉了。
Service和Activity通信
上面我们学习了Service的基本用法,启动Service之后,就可以在onCreate()或onStartCommand()方法里去执行一些具体的逻辑了。不过这样的话Service和Activity的关系并不大,只是Activity通知了Service一下:“你可以启动了。”然后Service就去忙自己的事情了。那么有没有什么办法能让它们俩的关联更多一些呢?比如说在Activity中可以指定让Service去执行什么任务。当然可以,只需要让Activity和Service建立关联就好了。
观察MyService中的代码,你会发现一直有一个onBind()方法我们都没有使用到,这个方法其实就是用于和Activity建立关联的,修改MyService中的代码,如下所示:
- public class MyService extends Service {
- public static final String TAG = "MyService";
- private MyBinder mBinder = new MyBinder();
- @Override
- public void onCreate() {
- super.onCreate();
- Log.d(TAG, "onCreate() executed");
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Log.d(TAG, "onStartCommand() executed");
- return super.onStartCommand(intent, flags, startId);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- Log.d(TAG, "onDestroy() executed");
- }
- @Override
- public IBinder onBind(Intent intent) {
- return mBinder;
- }
- class MyBinder extends Binder {
- public void startDownload() {
- Log.d("TAG", "startDownload() executed");
- // 执行具体的下载任务
- }
- }
- }
然后修改activity_main.xml中的代码,在布局文件中添加用于绑定Service和取消绑定Service的按钮:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <Button
- android:id="@+id/start_service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Start Service" />
- <Button
- android:id="@+id/stop_service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Stop Service" />
- <Button
- android:id="@+id/bind_service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Bind Service" />
- <Button
- android:id="@+id/unbind_service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Unbind Service"
- />
- </LinearLayout>
- public class MainActivity extends Activity implements OnClickListener {
- private Button startService;
- private Button stopService;
- private Button bindService;
- private Button unbindService;
- private MyService.MyBinder myBinder;
- private ServiceConnection connection = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- myBinder = (MyService.MyBinder) service;
- myBinder.startDownload();
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- startService = (Button) findViewById(R.id.start_service);
- stopService = (Button) findViewById(R.id.stop_service);
- bindService = (Button) findViewById(R.id.bind_service);
- unbindService = (Button) findViewById(R.id.unbind_service);
- startService.setOnClickListener(this);
- stopService.setOnClickListener(this);
- bindService.setOnClickListener(this);
- unbindService.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.start_service:
- Intent startIntent = new Intent(this, MyService.class);
- startService(startIntent);
- break;
- case R.id.stop_service:
- Intent stopIntent = new Intent(this, MyService.class);
- stopService(stopIntent);
- break;
- case R.id.bind_service:
- Intent bindIntent = new Intent(this, MyService.class);
- bindService(bindIntent, connection, BIND_AUTO_CREATE);
- break;
- case R.id.unbind_service:
- unbindService(connection);
- break;
- default:
- break;
- }
- }
- }
当然,现在Activity和Service其实还没关联起来了呢,这个功能是在Bind Service按钮的点击事件里完成的。可以看到,这里我们仍然是构建出了一个Intent对象,然后调用bindService()方法将Activity和Service进行绑定。bindService()方法接收三个参数,第一个参数就是刚刚构建出的Intent对象,第二个参数是前面创建出的ServiceConnection的实例,第三个参数是一个标志位,这里传入BIND_AUTO_CREATE表示在Activity和Service建立关联后自动创建Service,这会使得MyService中的onCreate()方法得到执行,但onStartCommand()方法不会执行。
然后如何我们想解除Activity和Service之间的关联怎么办呢?调用一下unbindService()方法就可以了,这也是Unbind Service按钮的点击事件里实现的逻辑。
现在让我们重新运行一下程序吧,在MainActivity中点击一下Bind Service按钮,LogCat里的打印日志如下图所示:
另外需要注意,任何一个Service在整个应用程序范围内都是通用的,即MyService不仅可以和MainActivity建立关联,还可以和任何一个Activity建立关联,而且在建立关联时它们都可以获取到相同的MyBinder实例。
如何销毁Service
在Service的基本用法这一部分,我们介绍了销毁Service最简单的一种情况,点击Start Service按钮启动Service,再点击Stop Service按钮停止Service,这样MyService就被销毁了,可以看到打印日志如下所示:
那么如果我们是点击的Bind Service按钮呢?由于在绑定Service的时候指定的标志位是BIND_AUTO_CREATE,说明点击Bind Service按钮的时候Service也会被创建,这时应该怎么销毁Service呢?其实也很简单,点击一下Unbind Service按钮,将Activity和Service的关联解除就可以了。
先点击一下Bind Service按钮,再点击一下Unbind Service按钮,打印日志如下所示:
以上这两种销毁的方式都很好理解。那么如果我们既点击了Start Service按钮,又点击了Bind Service按钮会怎么样呢?这个时候你会发现,不管你是单独点击Stop Service按钮还是Unbind Service按钮,Service都不会被销毁,必要将两个按钮都点击一下,Service才会被销毁。也就是说,点击Stop Service按钮只会让Service停止,点击Unbind Service按钮只会让Service和Activity解除关联,一个Service必须要在既没有和任何Activity关联又处理停止状态的时候才会被销毁。
为了证实一下,我们在Stop Service和Unbind Service按钮的点击事件里面加入一行打印日志:
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.start_service:
- Intent startIntent = new Intent(this, MyService.class);
- startService(startIntent);
- break;
- case R.id.stop_service:
- Log.d("MyService", "click Stop Service button");
- Intent stopIntent = new Intent(this, MyService.class);
- stopService(stopIntent);
- break;
- case R.id.bind_service:
- Intent bindIntent = new Intent(this, MyService.class);
- bindService(bindIntent, connection, BIND_AUTO_CREATE);
- break;
- case R.id.unbind_service:
- Log.d("MyService", "click Unbind Service button");
- unbindService(connection);
- break;
- default:
- break;
- }
- }
我们应该始终记得在Service的onDestroy()方法里去清理掉那些不再使用的资源,防止在Service被销毁后还会有一些不再使用的对象仍占用着内存。
Service和Thread的关系
不少Android初学者都可能会有这样的疑惑,Service和Thread到底有什么关系呢?什么时候应该用Service,什么时候又应该用Thread?答案可能会有点让你吃惊,因为Service和Thread之间没有任何关系!
之所以有不少人会把它们联系起来,主要就是因为Service的后台概念。Thread我们大家都知道,是用于开启一个子线程,在这里去执行一些耗时操作就不会阻塞主线程的运行。而Service我们最初理解的时候,总会觉得它是用来处理一些后台任务的,一些比较耗时的操作也可以放在这里运行,这就会让人产生混淆了。但是,如果我告诉你Service其实是运行在主线程里的,你还会觉得它和Thread有什么关系吗?让我们看一下这个残酷的事实吧。
在MainActivity的onCreate()方法里加入一行打印当前线程id的语句:
- Log.d("MyService", "MainActivity thread id is " + Thread.currentThread().getId());
- Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId());
现在重新运行一下程序,并点击Start Service按钮,会看到如下打印日志:
可以看到,它们的线程id完全是一样的,由此证实了Service确实是运行在主线程里的,也就是说如果你在Service里编写了非常耗时的代码,程序必定会出现ANR的。
你可能会惊呼,这不是坑爹么!?那我要Service又有何用呢?其实大家不要把后台和子线程联系在一起就行了,这是两个完全不同的概念。Android的后台就是指,它的运行是完全不依赖UI的。即使Activity被销毁,或者程序被关闭,只要进程还在,Service就可以继续运行。比如说一些应用程序,始终需要与服务器之间始终保持着心跳连接,就可以使用Service来实现。你可能又会问,前面不是刚刚验证过Service是运行在主线程里的么?在这里一直执行着心跳连接,难道就不会阻塞主线程的运行吗?当然会,但是我们可以在Service中再创建一个子线程,然后在这里去处理耗时逻辑就没问题了。
额,既然在Service里也要创建一个子线程,那为什么不直接在Activity里创建呢?这是因为Activity很难对Thread进行控制,当Activity被销毁之后,就没有任何其它的办法可以再重新获取到之前创建的子线程的实例。而且在一个Activity中创建的子线程,另一个Activity无法对其进行操作。但是Service就不同了,所有的Activity都可以与Service进行关联,然后可以很方便地操作其中的方法,即使Activity被销毁了,之后只要重新与Service建立关联,就又能够获取到原有的Service中Binder的实例。因此,使用Service来处理后台任务,Activity就可以放心地finish,完全不需要担心无法对后台任务进行控制的情况。
一个比较标准的Service就可以写成:
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- // 开始执行后台任务
- }
- }).start();
- return super.onStartCommand(intent, flags, startId);
- }
- class MyBinder extends Binder {
- public void startDownload() {
- new Thread(new Runnable() {
- @Override
- public void run() {
- // 执行具体的下载任务
- }
- }).start();
- }
- }
创建前台Service
Service几乎都是在后台运行的,一直以来它都是默默地做着辛苦的工作。但是Service的系统优先级还是比较低的,当系统出现内存不足情况时,就有可能会回收掉正在后台运行的Service。如果你希望Service可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台Service。前台Service和普通Service最大的区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。当然有时候你也可能不仅仅是为了防止Service被回收才使用前台Service,有些项目由于特殊的需求会要求必须使用前台Service,比如说墨迹天气,它的Service在后台更新天气数据的同时,还会在系统状态栏一直显示当前天气的信息,如下图所示:
那么我们就来看一下如何才能创建一个前台Service吧,其实并不复杂,修改MyService中的代码,如下所示:
- public class MyService extends Service {
- public static final String TAG = "MyService";
- private MyBinder mBinder = new MyBinder();
- @Override
- public void onCreate() {
- super.onCreate();
- Notification notification = new Notification(R.drawable.ic_launcher,
- "有通知到来", System.currentTimeMillis());
- Intent notificationIntent = new Intent(this, MainActivity.class);
- PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
- notificationIntent, 0);
- notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",
- pendingIntent);
- startForeground(1, notification);
- Log.d(TAG, "onCreate() executed");
- }
- .........
- }
现在重新运行一下程序,并点击Start Service或Bind Service按钮,MyService就会以前台Service的模式启动了,并且在系统状态栏会弹出一个通栏图标,下拉状态栏后可以看到通知的详细内容,如下图所示。
远程服务实例:
在上篇文章中我们知道了,Service其实是运行在主线程里的,如果直接在Service中处理一些耗时的逻辑,就会导致程序ANR。
让我们来做个实验验证一下吧,修改上一篇文章中创建的ServiceTest项目,在MyService的onCreate()方法中让线程睡眠60秒,如下所示:
- public class MyService extends Service {
- ......
- @Override
- public void onCreate() {
- super.onCreate();
- Log.d(TAG, "onCreate() executed");
- try {
- Thread.sleep(60000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- ......
- }
重新运行后,点击一下Start Service按钮或Bind Service按钮,程序就会阻塞住并无法进行任何其它操作,过一段时间后就会弹出ANR的提示框,如下图所示。
之前我们提到过,应该在Service中开启线程去执行耗时任务,这样就可以有效地避免ANR的出现。
那么本篇文章的主题是介绍远程Service的用法,如果将MyService转换成一个远程Service,还会不会有ANR的情况呢?让我们来动手尝试一下吧。
将一个普通的Service转换成远程Service其实非常简单,只需要在注册Service的时候将它的android:process属性指定成:remote就可以了,代码如下所示:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.servicetest"
- android:versionCode="1"
- android:versionName="1.0" >
- ......
- <service
- android:name="com.example.servicetest.MyService"
- android:process=":remote" >
- </service>
- </manifest>
为什么将MyService转换成远程Service后就不会导致程序ANR了呢?这是由于,使用了远程Service后,MyService已经在另外一个进程当中运行了,所以只会阻塞该进程中的主线程,并不会影响到当前的应用程序。
为了证实一下MyService现在确实已经运行在另外一个进程当中了,我们分别在MainActivity的onCreate()方法和MyService的onCreate()方法里加入一行日志,打印出各自所在的进程id,如下所示:
- Log.d("TAG", "process id is " + Process.myPid());
可以看到,不仅仅是进程id不同了,就连应用程序包名也不一样了,MyService中打印的那条日志,包名后面还跟上了:remote标识。
那既然远程Service这么好用,干脆以后我们把所有的Service都转换成远程Service吧,还省得再开启线程了。其实不然,远程Service非但不好用,甚至可以称得上是较为难用。一般情况下如果可以不使用远程Service,就尽量不要使用它。
下面就来看一下它的弊端吧,首先将MyService的onCreate()方法中让线程睡眠的代码去除掉,然后重新运行程序,并点击一下Bind Service按钮,你会发现程序崩溃了!为什么点击Start Service按钮程序就不会崩溃,而点击Bind Service按钮就会崩溃呢?这是由于在Bind Service按钮的点击事件里面我们会让MainActivity和MyService建立关联,但是目前MyService已经是一个远程Service了,Activity和Service运行在两个不同的进程当中,这时就不能再使用传统的建立关联的方式,程序也就崩溃了。
那么如何才能让Activity与一个远程Service建立关联呢?这就要使用AIDL来进行跨进程通信了(IPC)。
AIDL(Android Interface Definition Language)是Android接口定义语言的意思,它可以用于让某个Service与多个应用程序组件之间进行跨进程通信,从而可以实现多个应用程序共享同一个Service的功能。
下面我们就来一步步地看一下AIDL的用法到底是怎样的。首先需要新建一个AIDL文件,在这个文件中定义好Activity需要与Service进行通信的方法。新建MyAIDLService.aidl文件,代码如下所示:
- package com.example.servicetest;
- interface MyAIDLService {
- int plus(int a, int b);
- String toUpperCase(String str);
- }
然后修改MyService中的代码,在里面实现我们刚刚定义好的MyAIDLService接口,如下所示:
- public class MyService extends Service {
- ......
- @Override
- public IBinder onBind(Intent intent) {
- return mBinder;
- }
- MyAIDLService.Stub mBinder = new Stub() {
- @Override
- public String toUpperCase(String str) throws RemoteException {
- if (str != null) {
- return str.toUpperCase();
- }
- return null;
- }
- @Override
- public int plus(int a, int b) throws RemoteException {
- return a + b;
- }
- };
- }
接下来修改MainActivity中的代码,如下所示:
- public class MainActivity extends Activity implements OnClickListener {
- private Button startService;
- private Button stopService;
- private Button bindService;
- private Button unbindService;
- private MyAIDLService myAIDLService;
- private ServiceConnection connection = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- myAIDLService = MyAIDLService.Stub.asInterface(service);
- try {
- int result = myAIDLService.plus(3, 5);
- String upperStr = myAIDLService.toUpperCase("hello world");
- Log.d("TAG", "result is " + result);
- Log.d("TAG", "upperStr is " + upperStr);
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- }
- };
- ......
- }
现在重新运行程序,并点击一下Bind Service按钮,可以看到打印日志如下所示:
由此可见,我们确实已经成功实现跨进程通信了,在一个进程中访问到了另外一个进程中的方法。
不过你也可以看出,目前的跨进程通信其实并没有什么实质上的作用,因为这只是在一个Activity里调用了同一个应用程序的Service里的方法。而跨进程通信的真正意义是为了让一个应用程序去访问另一个应用程序中的Service,以实现共享Service的功能。那么下面我们自然要学习一下,如何才能在其它的应用程序中调用到MyService里的方法。
在上一篇文章中我们已经知道,如果想要让Activity与Service之间建立关联,需要调用bindService()方法,并将Intent作为参数传递进去,在Intent里指定好要绑定的Service,示例代码如下:
- Intent bindIntent = new Intent(this, MyService.class);
- bindService(bindIntent, connection, BIND_AUTO_CREATE);
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.servicetest"
- android:versionCode="1"
- android:versionName="1.0" >
- ......
- <service
- android:name="com.example.servicetest.MyService"
- android:process=":remote" >
- <intent-filter>
- <action android:name="com.example.servicetest.MyAIDLService"/>
- </intent-filter>
- </service>
- </manifest>
这就说明,MyService可以响应带有com.example.servicetest.MyAIDLService这个action的Intent。
现在重新运行一下程序,这样就把远程Service端的工作全部完成了。然后创建一个新的Android项目,起名为ClientTest,我们就尝试在这个程序中远程调用MyService中的方法。
ClientTest中的Activity如果想要和MyService建立关联其实也不难,首先需要将MyAIDLService.aidl文件从ServiceTest项目中拷贝过来,注意要将原有的包路径一起拷贝过来,完成后项目的结构如下图所示:
然后打开或新建activity_main.xml,在布局文件中也加入一个Bind Service按钮:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- >
- <Button
- android:id="@+id/bind_service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Bind Service"
- />
- </LinearLayout>
- public class MainActivity extends Activity {
- private MyAIDLService myAIDLService;
- private ServiceConnection connection = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- myAIDLService = MyAIDLService.Stub.asInterface(service);
- try {
- int result = myAIDLService.plus(50, 50);
- String upperStr = myAIDLService.toUpperCase("comes from ClientTest");
- Log.d("TAG", "result is " + result);
- Log.d("TAG", "upperStr is " + upperStr);
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button bindService = (Button) findViewById(R.id.bind_service);
- bindService.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent("com.example.servicetest.MyAIDLService");
- bindService(intent, connection, BIND_AUTO_CREATE);
- }
- });
- }
- }
在当前Activity和MyService建立关联之后,我们仍然是调用了plus()和toUpperCase()这两个方法,远程的MyService会对传入的参数进行处理并返回结果,然后将结果打印出来。
这样的话,ClientTest中的代码也就全部完成了,现在运行一下这个项目,然后点击Bind Service按钮,此时就会去和远程的MyService建立关联,观察LogCat中的打印信息如下所示:
不用我说,大家都已经看出,我们的跨进程通信功能已经完美实现了。
不过还有一点需要说明的是,由于这是在不同的进程之间传递数据,Android对这类数据的格式支持是非常有限的,基本上只能传递Java的基本数据类型、字符串、List或Map等。那么如果我想传递一个自定义的类该怎么办呢?这就必须要让这个类去实现Parcelable接口,并且要给这个类也定义一个同名的AIDL文件。