[android] 03_绑定开启服务bindservice()

Android 4.0

绑定开启服务bindservice() 

绑定服务类似人放风筝

服务一旦被创建,就不会重新创建了.
服务的oncreate方法只会执行一次,如果服务已经开启,就不会再去执行oncreate方法
服务在停止的时候,会调用ondestroy方法
 
每一次开启startService()服务的时候 都会调用 onStartCommand()  onStart();
 
服务有两种开启方式:
1. startService(); 服务一旦开启就跟开启者(activity)没有什么关系.activity挂了,
服务还会开心的在后台运行.
 
2. bindService();  服务跟activity就有了千丝万缕的联系. 如果调用者activity挂了
服务也跟着挂了.  不求同时生,但求同时死.
服务只能被显示的解除绑定一次,多次的解除绑定服务 应用程序会报异常

开启该服务的组件挂了,服务也挂了;但服务挂了,该组件不会挂
ServiceConnection //Interface for monitoring the state of an application service

问题1、一个开启服务的Activity,如果其绑定的服务还在运行,此时destroy该activity,那么会报异常
异常:E/ActivityThread(944): Activity cn.zengfansheng.serviceLifecycle.MainActivity has leaked ServiceConnection cn.zengfansheng.serviceLifecycle.MainActivity$1@40fa3640 that was originally bound here
解决:重写Activity的onDestroy()方法,在Activity被销毁时,解除和服务的绑定
// Activity挂了,将服务和其解除连接
@Override
protected void onDestroy() {
    super.onDestroy();// 这句不能省略,否则会报异常
    this.unbindService(conn);// Disconnect from an application service
}


问题2、服务只能被解除绑定一次,解除第二次,那么会报异常。
E/AndroidRuntime(1250): java.lang.IllegalStateException: Could not execute method of the activity



问题3、如果手工解除绑定服务,在activity的onDestroy()又解除绑定,会报异常 
E/AndroidRuntime(1367): java.lang.RuntimeException: Unable to destroy activity {cn.zengfansheng.bindserviceLifecycle/cn.zengfansheng.serviceLifecycle.MainActivity}: java.lang.IllegalArgumentException: Service not registered: cn.zengfansheng.serviceLifecycle.MainActivity$1@40faa888
问题2和问题3解决:
// TODO 解除绑定服务方案二
if (conn != null) {
    this.unbindService(conn);
    conn = null;
}
// TODO:解除绑定方案一
/*try {
    this.unbindService(conn);// 2、解除绑定服务
    conn = null;
} catch (Exception e) {
    e.printStackTrace();
}*/