《Android攻略》客户端和Service交互

1)客户端实现android.content.ServiceConnection的一个子类,随着Service的启动和停止,为了获得Service的信息重载其中的抽象方法void onServiceConnected(ComponentName className,IBinder service)和

void onServiceDisconnected(ComponentName name)。当bindService(Intent,ServiceConnection,int)返回ture时,如果建立了到Service的连接,就会调用前一个方法;传递给该方法的IBinder参数与onBind(Intent)的返回值相同。如果Service连接丢失 ,就会调用后一个方法。

 连接丢失通常发生在提供Service的进程崩溃或被临时终止的情况下。只要ServiceConnection实例本身没有被删除,与Service的绑定就始终处于活跃状态,当Service再次运行时会调用onServiceConnected(ComponentName,IBinder)。

2)客户端将ServiceConnection子类对象传递给bindService(Intent,ServiceConnection,int)方法。

 客户端调用void unbindService(ServiceConnection conn)方法与Service断开连接。断开连接后,Service重启时,该组件也不会收到调用。如果没有其他绑定,该Service随时可以停止。

在Service可以停止Service之前,会调用服务的boolean onUnbind(Intent intent)生命周期回调方法,其中的Intent对象会传递给unbindService(ServiceConnection)。假设onUnbind没有返回ture,则销毁该服务。否则每次绑定到该Service时都调用void onRebind(Intent intent)生命周期回调方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章