我是一个在单独进程中运行的绑定服务
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
方法未被调用!同时调用onUnbind
和onDestroy
服务方法。
更令人惊讶的是,我可以使用先前serviceMessenger
中生成的bind
与服务进行通信!
摘要
1.当我调用onServiceDisconnected
方法时,为什么unBind
未被调用?
2-为什么可以与因unBind
呼叫而销毁的服务进行通信?