Bind Service

本文简述Service的第二种启动方式,bindService。

bindService有四个方法控制:

  • onCreate()在service被创建时调用
  • onBind()在service被绑定时调用
  • onUnBind()在service解绑时调用
  • onDestroy()在service终止时调用

    下面通过代码来分析:

    MainActivity.java
    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
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    package com.example.ahtcfg24.bindservicedemo;

    import android.app.Activity;
    import android.app.Service;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;

    public class MainActivity extends Activity {
    public static final String TAG = "ServiceConnect";
    private Button button, button2, button3, button4;
    private ServiceConnection serviceConnection;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    button2 = (Button) findViewById(R.id.button2);
    button3 = (Button) findViewById(R.id.button3);
    button4 = (Button) findViewById(R.id.button4);


    button.setOnClickListener(new ButtonListener());
    button2.setOnClickListener(new ButtonListener());
    button3.setOnClickListener(new ButtonListener());
    button4.setOnClickListener(new ButtonListener());

    }

    /**
    * 如果在service绑定的Activity被结束之后,service却没有解绑就会导致后台出现异常
    * 或者在连接中断后去解绑也会出现异常
    * 这样做可保障不出现上述异常
    */

    @Override
    protected void onDestroy() {
    super.onDestroy();
    unbindService(serviceConnection);
    }

    private class ButtonListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
    intent = new Intent(MainActivity.this, MyService.class);
    switch (v.getId()) {
    case R.id.button:
    startService(intent);
    break;
    case R.id.button2:
    stopService(intent);
    break;
    case R.id.button3:
    serviceConnection = new ServiceConnection() {
    /**
    * 该方法只在onBind方法有不为空的返回值时才会被调用
    *
    * @param name 与当前组件(Activity)绑定的Service名称
    * @param service 从绑定的Service中的onBind方法中返回的IBender实例
    */

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    System.out.println(name);
    System.out.println(service);
    Log.i(TAG, "--->onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    Log.i(TAG, "--->onServiceDisconnected");
    }
    };
    bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
    //第三个参数是指定Service创建类型,一般是BIND_AUTO_CREATE
    break;
    case R.id.button4:
    unbindService(serviceConnection);
    break;
    default:
    break;
    }
    }
    }
    }

activity_main.xml

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
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">


<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button4"
android:layout_alignStart="@+id/button4"
android:layout_below="@+id/button2"
android:text="绑定Serevice"/>

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button3"
android:layout_centerHorizontal="true"
android:text="解绑Service"/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button4"
android:layout_alignParentTop="true"
android:layout_alignStart="@+id/button4"
android:text="启动service"/>

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true"
android:text="停止Service"/>
</RelativeLayout>

MyService.java

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
53
54
55
56
57
58
59
package com.example.ahtcfg24.bindservicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
public static final String TAG = "MyService";

/**
* @param intent
* @return bind service时需要使得onBind方法返回一个IBinder类型的类,否则不会调用onServiceConnected,而Binder类恰好实现了IBinder接口
*/

@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "--->onBind");
return new Binder() {
public String toString() {
return "这是个Binder对象";
}
};

}

@Override
public void onCreate() {
Log.i(TAG, "--->onCreate");

super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "--->onStartCommand");
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
Log.i(TAG, "--->onDestroy");

super.onDestroy();

}

@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "--->onUnbind");
return super.onUnbind(intent);
}

@Override
public void onStart(Intent intent, int startId) {
Log.i(TAG, "--->onStart");
super.onStart(intent, startId);
}
}

查看代码

结果显而易见,就不再赘述,只给出结论:

  • 当执行bindService()时,先执行OnCreate()来创建一个Service,然后执行onBind()方法来绑定,然后执行onServiceConnected,如果这个Service已经创建过了,那么就跳过onCreate()这一步,而直接取执行onBind()、onServiceConnected(),如果这个Service既创建过了又绑定过了,那么就只执行onServiceConnected()。
  • 绑定之后才能执行unbindService(),否则会抛出异常。执行unbindService()时,就会执行onUnBind(),接着执行onDestroy()。另一方面,如果绑定了之后退出程序,那么也会自动调用onUnBind(),并且执行onDestroy()。
  • 此外,如果绑定前或者绑定后调用了startService(),那么,解绑或者退出都不会执行onDestroy(),该服务会常驻后台直到被强制杀死)
  • onServiceDisconnected()方法不会在解绑时调用,只有在服务异常中断时才会调用。
  • 总而言之,startService()把服务放在可见的后台,生命周期与启动它的组件无关,BindService()把服务放在不可见的后台,生命周期与启动它的组件保持一致

参考资料

(本文系作者原创,转载请注明出处)