Android开发之Service的写法以及与Activity的通信

Service的总结:

1.按运行地点分类:

类别 区别  优点 缺点   应用
本地服务(Local) 该服务依附在主进程上,  服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外Local服务因为是在同一进程因此不需要IPC,也不需要AIDL。相应bindService会方便很多。  主进程被Kill后,服务便会终止。  非常常见的应用如:HTC的音乐播放服务,天天动听音乐播放服务。
远程服务(Remote) 该服务是独立的进程,  服务为独立的进程,对应进程名格式为所在包名加上你指定的android:process字符串。由于是独立的进程,因此在Activity所在进程被Kill的时候,该服务依然在运行,不受其他进程影响,有利于为多个进程提供服务具有较高的灵活性。  该服务是独立的进程,会占用一定资源,并且使用AIDL进行IPC稍微麻烦一点。  一些提供系统服务的Service,这种Service是常驻的。

Remote服务,比较常见的是360,qq,豌豆荚等,都使用了Remote,这种服务常驻,保证就算Acticity被杀掉了,依旧可以使用。

2.按运行类型分类:

类别 区别 应用
前台服务 会在通知一栏显示 ONGOING 的 Notification, 当服务被终止的时候,通知一栏的 Notification 也会消失,这样对于用户有一定的通知作用。常见的如音乐播放服务。
后台服务 默认的服务即为后台服务,即不会在通知一栏显示 ONGOING 的 Notification。 当服务被终止的时候,用户是看不到效果的。某些不需要运行或终止提示的服务,如天气更新,日期同步,邮件同步等。

3.按使用方式分类:

类别 区别
startService 启动的服务 主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService
bindService 启动的服务 该方法启动的服务要进行通信。停止服务使用unbindService
startService 同时也 bindService 启动的服务 停止服务应同时使用stepService与unbindService

4.Service的生命周期

onCreate()   onStartCommand()   onBind()    onUnbind()    onDestory()

1). 被启动的服务的生命周期(Context.startService()):如果一个Service被某个Activity 调用 Context.startService() 方法启动,那么不管是否有Activity使用bindService()绑定或unbindService()解除绑定到该Service,该Service都在后台运行。如果一个Service被startService() 方法多次启动,那么onCreate()方法只会调用一次,onStartCommand()将会被调用多次(对应调用startService的次数),并且系统只会创建Service的一个实例(因此你应该知道只需要一次stopService()调用)。该Service将会一直在后台运行,而不管对应程序的Activity是否在运行,直到被调用stopService(),或自身的stopSelf()方法。当然如果系统资源不足,android系统也可能结束服务。

2). 被绑定的服务的生命周期(Context.bindService()):如果一个Service被某个Activity 调用 Context.bindService() 方法绑定启动,不管调用 bindService() 调用几次,onCreate()方法都只会调用一次,同时onStartCommand()方法始终不会被调用。当连接建立之后,Service将会一直运行,除非调用Context.unbindService() 断开连接或者之前调用bindService 的 Context 不存在了(如Activity被finish的时候),系统将会自动停止Service,对应onDestroy()将被调用。

3). 被启动又被绑定的服务的生命周期:如果一个Service又被启动又被绑定,则该Service将会一直在后台运行。并且不管如何调用,onCreate()始终只会调用一次,对应startService()调用多少次,Service的onStartCommand()便会调用多少次。调用unbindService将不会停止Service,而必须调用 stopService() 或 Service的 stopSelf() 来停止服务。

4). 当服务被停止时清除服务:当一个Service被终止(1、调用stopService;2、调用stopSelf;3、不再有绑定的连接(没有被启动))时,onDestroy()方法将会被调用,在这里你应当做一些清除工作,如停止在Service中创建并运行的线程。

特别注意:

1、你应当知道在调用 bindService 绑定到Service的时候,你就应当保证在某处调用 unbindService 解除绑定(尽管 Activity 被 finish 的时候绑定会自动解除,并且Service会自动停止);

2、你应当注意 使用 startService 启动服务之后,一定要使用 stopService停止服务,不管你是否使用bindService;

3、同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindService与stopService同时调用,才能终止 Service,不管 startService 与 bindService 的调用顺序,如果先调用 unbindService 此时服务不会自动终止,再调用 stopService 之后服务才会停止,如果先调用 stopService 此时服务也不会终止,而再调用 unbindService 或者 之前调用 bindService 的 Context 不存在了(如Activity 被 finish 的时候)之后服务才会自动停止;

4、当在旋转手机屏幕的时候,当手机屏幕在“横”“竖”变换时,此时如果你的 Activity 如果会自动旋转的话,旋转其实是 Activity 的重新创建,因此旋转之前的使用 bindService 建立的连接便会断开(Context 不存在了),对应服务的生命周期与上述相同。

5.startService()启动服务

想要用 startService 启动服务,不管Local 还是 Remote 们需要做的工作都是一样的。

根据上面的生命周期,给出 Service 中的代码框架:

 1 import android.app.Service;
 2 import android.content.Intent;
 3 import android.os.IBinder;
 4 
 5 public class IService extends Service{
 6     
 7     //onBind 是 Service 的虚方法,因此我们不得不实现它。返回 null,表示客服端不能建立到此服务的连接。
 8     @Override
 9     public IBinder onBind(Intent intent) {
10         return null;
11     }
12     
13     @Override
14     public void onCreate() {
15         super.onCreate();
16     }
17     
18     @Override
19     public int onStartCommand(Intent intent, int flags, int startId) {
20         return super.onStartCommand(intent, flags, startId);
21     }
22     
23     @Override
24     public void onDestroy() {
25         super.onDestroy();
26     }
27 
28 }
View Code

启动与停止 Service 的代码:

1 //启动Service服务代码
2 Intent startIntent = new Intent(MainActivity.this, MyService.class);
3 startService(startIntent);
4 
5 
6 //停止Service服务代码
7 Intent stopIntent = new Intent(MainActivity.this, MyService.class);
8 stopService(stopIntent);
View Code

6.Local 与 Remote 服务绑定:

1). Local 服务绑定:首先在 Service 中我们需要实现 Service 的抽象方法 onBind,并返回一个实现 IBinder 接口的对象。

Service 中的代码:

 1 import android.app.Service;
 2 import android.content.Intent;
 3 import android.os.Binder;
 4 import android.os.IBinder;
 5 import android.text.format.Time;
 6 
 7 public class MyService extends Service {
 8     
 9     private static final String TAG = "servicedemo";
10 
11     private MyBinder mBinder = new MyBinder();  //创建 mBinder
12     
13    //在 Local Service 中我们直接继承 Binder 而不是 IBinder,因为 Binder 实现了 IBinder 接口,这样我们可以少做很多工作。
14    public class MyBinder extends Binder{
15        MyService getService(){
16                  //获取 Service 实例
17            return MyService.this;
18        }
19    }
20 
21     @Override
22     public IBinder onBind(Intent intent) {
23                 //返回 MyBinder 对象
24         return mBinder;
25     }
26 
27     @Override
28     public void onCreate() {
29         super.onCreate();
30     
31     }
32 
33 
34     @Override
35     public void onDestroy() {
36         super.onDestroy();
37     }
38 
39     @Override
40     public boolean onUnbind(Intent intent) {
41         return super.onUnbind(intent);
42     }
43 
44     public String getSystemTime() {
45         Time t = new Time();
46         t.setToNow();
47         return t.toString();
48 
49     }
50 
51 }
View Code

上面的代码关键之处,在于 onBind(Intent) 这个方法 返回了一个实现了 IBinder 接口的对象,这个对象将用于绑定Service 的 Activity 与 Local Service 通信。

下面是 Activity 中的代码:

 1 import com.example.servicedemo.MyService.MyBinder;
 2 import android.app.Activity;
 3 import android.content.ComponentName;
 4 import android.content.Intent;
 5 import android.content.ServiceConnection;
 6 import android.os.Bundle;
 7 import android.os.IBinder;
 8 import android.view.View;
 9 import android.view.View.OnClickListener;
10 import android.widget.Button;
11 import android.widget.TextView;
12 
13 public class MainActivity extends Activity implements OnClickListener {
14 
15     private TextView tv;
16     private Button btn_BindService,btn_UnbindService;
17     private boolean isBinder;
18 
19     private ServiceConnection mServiceConnection = new ServiceConnection() {
20 
21         @Override
22         public void onServiceDisconnected(ComponentName name) {
23 
24         }
25 
26         @Override
27         public void onServiceConnected(ComponentName name, IBinder service) {
28             MyService.MyBinder myBinder = (MyBinder) service;
29             tv.setText(myBinder.getService().getSystemTime());
30 
31         }
32     };
33 
34     @Override
35     protected void onCreate(Bundle savedInstanceState) {
36         super.onCreate(savedInstanceState);
37         setContentView(R.layout.activity_main);
38         init();
39     }
40 
41     private void init() {
42         tv = (TextView) findViewById(R.id.tv);
43         btn_BindService = (Button) findViewById(R.id.btn_BindService);
44         btn_UnbindService = (Button) findViewById(R.id.btn_UnbindService);
45 
46         btn_BindService.setOnClickListener(this);
47         btn_UnbindService.setOnClickListener(this);
48     }
49 
50     @Override
51     public void onClick(View v) {
52         switch (v.getId()) {
53         case R.id.btn_BindService:
54             Intent bindIntent = new Intent(MainActivity.this, MyService.class);
55             bindService(bindIntent, mServiceConnection, BIND_AUTO_CREATE);
56             isBinder=true;
57             break;
58         case R.id.btn_UnbindService:
59             if (isBinder) {
60                 unbindService(mServiceConnection);
61             }
62             break;
63             
64         default:
65             break;
66         }
67     }
68 }
View Code

在 Activity 中,我们通过 ServiceConnection 接口来取得建立连接 与 连接意外丢失的回调。bindService有三个参数,第一个是用于区分 Service 的Intent 与 startService 中的 Intent 一致,第二个是实现了 ServiceConnection 接口的对象,最后一个是 flag 标志位。有两个flag,BIND_DEBUG_UNBIND 与 BIND_AUTO_CREATE,前者用于调试(详细内容可以查看javadoc 上面描述的很清楚),后者默认使用。unbindService 解除绑定,参数则为之前创建的 ServiceConnection 接口对象。另外,多次调用 unbindService 来释放相同的连接会抛出异常,因此我创建了一个 boolean 变量来判断是否 unbindService 已经被调用过。

2). Remote 服务绑定:Remote 的服务绑定由于服务是在另外一个进程,因此需要用到 android 的 IPC 机制。

特别注意:

1、Service.onBind如果返回null,则调用 bindService 会启动 Service,但不会连接上 Service,因此 ServiceConnection.onServiceConnected 不会被调用,但你任然需要使用 unbindService 函数断开它,这样 Service 才会停止。

原文地址:https://www.cnblogs.com/liyiran/p/4903825.html