今天发现一个Service的小问题
发现ServiceConnection的onServiceConnected方法总是不会调用,不管你调用unbind 或者 stop的方法,都不能回调到onServiceConnected,心想service断开连接时候应该调用的啊。。。而且,我想用一个布朗值去代表服务是否断开,只能在这里赋值更改,导致unbind时候不能判断服务是否已经unbind,程序就崩溃了。。。。。 直接查官方文档:
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();
}
?总之就是,这个方法是在服务异常断开连接时候才会被调用,通常是进程crash时候,所以不管你是否调用stop/unbind 都不会回调这个接口。 而且当进程被kill掉,在locat中也难以看到回调这个方法,因为service也是和我们的app通常在一个进程。
注意官方给的源码实例中选择用mShouldUnbind 在bind时候赋值的方式来防治多次unbind
void doBindService() {
// Attempts to 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).
if (bindService(new Intent(Binding.this, LocalService.class),
mConnection, Context.BIND_AUTO_CREATE)) {
mShouldUnbind = true;
} else {
Log.e("MY_APP_TAG", "Error: The requested service doesn't " +
"exist, or this client isn't allowed access to it.");
}
}
void doUnbindService() {
if (mShouldUnbind) {
// Release information about the service's state.
unbindService(mConnection);
mShouldUnbind = false;
}
}
?所以遇到问题还是乖乖看官方文档吧,自己写半天还是在坑里给自己挖坑。。。。。
|