Context.bindService()详解

来源:互联网 发布:我的手机淘宝怎么打不开 编辑:程序博客网 时间:2024/06/06 03:44

这几天卡在服务绑定上面了,网上查了一圈没看懂,只好Google 文档了,开始我是拒绝的,但是查完之后,对它爱不释手了!直接贴一段Google官方关于bindService()的解释:

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (callingonCreate() while doing so), but does not call onStartCommand(). The client will receive theIBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has beenwritten in aidl.

原来bindService(Intent service,ServiceConnection conn,int flags)的参数是这样来的啊,首先Intent就是你要绑定或者通信的服务,ServiceConnection是服务绑定的必须要实现的类,在这个类中必须实现两个函数。1:onServiceDisconnection(),在解除绑定时调用 2:

onServiceConnected(ComponentName className, IBinder service)
在成功绑定时调用,其中这个IBinder是Service类中onBind()返回的结果。

private LocalService mBoundService;private ServiceConnection mConnection = new ServiceConnection() {    public void onServiceConnected(ComponentName className, IBinder service) {        // This is called when the connection with the service has been        // established, giving us the service object we can use to        // interact with the service.  Because we have bound to a explicit        // service that we know is running in our own process, we can        // cast its IBinder to a concrete class and directly access it.        mBoundService = ((LocalService.LocalBinder)service).getService();        // Tell the user about this for our demo.        Toast.makeText(Binding.this, R.string.local_service_connected,                Toast.LENGTH_SHORT).show();    }    public void onServiceDisconnected(ComponentName className) {        // This is called when the connection with the service has been        // unexpectedly disconnected -- that is, its process crashed.        // Because it is running in our same process, we should never        // see this happen.        mBoundService = null;        Toast.makeText(Binding.this, R.string.local_service_disconnected,                Toast.LENGTH_SHORT).show();    }};void doBindService() {    // Establish a connection with the service.  We use an explicit    // class name because we want a specific service implementation that    // we know will be running in our own process (and thus won't be    // supporting component replacement by other applications).    bindService(new Intent(Binding.this,             LocalService.class), mConnection, Context.BIND_AUTO_CREATE);    mIsBound = true;}void doUnbindService() {    if (mIsBound) {        // Detach our existing connection.        unbindService(mConnection);        mIsBound = false;    }}@Overrideprotected void onDestroy() {    super.onDestroy();    doUnbindService();}


0 0