unBind绑定服务

时间:2015-06-14 07:15:24

标签: android service ipc

我是一个在单独进程中运行的绑定服务

public class DownloadService extends Service {

private Looper mLooper;
private ServiceHandler mServiceHandler;

private Messenger messenger;
private Messenger uiMessenger;

@Override
public void onCreate() {
    super.onCreate();

    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_FOREGROUND);
    thread.start();

    mLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mLooper);

    messenger = new Messenger(mServiceHandler);
}

private class ServiceHandler extends Handler {

    public ServiceHandler() {

    }

    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {

        switch (msg.what) {

        case MSG_DOWNLOAD_REQUEST:

            String url = msg.getData().getString("url");

            Log.d("test", url);

            // download(url);

            break;

        default:
            super.handleMessage(msg);
            break;
        }
    }
}

@Override
public IBinder onBind(Intent intent) {

    Log.d("test", "onBind");

    return messenger.getBinder();
}

@Override
public void onRebind(Intent intent) {
    Log.d("test", "onRebind");
    super.onRebind(intent);
}

@Override
public boolean onUnbind(Intent intent) {

    Log.d("test", "onUnbind");

    return super.onUnbind(intent);
}

@Override
public void onDestroy() {

    Log.d("test", "onDestroy");

    super.onDestroy();
}

}

还有像这样的ServiceConnection:

serviceConnection = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {

                serviceMessenger = null;
                isConnected = false;

                Log.d("test", "disconn");
            }

            @Override
            public void onServiceConnected(ComponentName name,
                    IBinder service) {

                if (serviceMessenger == null) {

                    serviceMessenger = new Messenger(service);
                }

                isConnected = true;

                Log.d("test", "conn");

                send();
            }
        };

请求绑定服务

Intent intent = new Intent(context, DownloadService.class);
        context.bindService(intent, serviceConnection,
                Context.BIND_AUTO_CREATE);

和unBind请求

        context.unbindService(serviceConnection);

调用bindService后,每件事情都很好并且正常工作并调用了onServiceConnected ServiceConnection方法,但是当我调用unBind方法时,onServiceDisconnected方法未被调用!同时调用onUnbindonDestroy服务方法。

更令人惊讶的是,我可以使用先前serviceMessenger中生成的bind与服务进行通信!

摘要
1.当我调用onServiceDisconnected方法时,为什么unBind未被调用? 2-为什么可以与因unBind呼叫而销毁的服务进行通信?

0 个答案:

没有答案