这几天卡在服务绑定上面了,网上查了一圈没看懂,只好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 (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder 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 been written in aidl.

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

onServiceConnected(ComponentName className, IBinder service)

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,

    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,

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.
        mIsBound = false;

protected void onDestroy() {

个人分类: Android
想对作者说点什么? 我来说一句