一般来说,无论bindService()
调用返回true还是false,ServiceConnection总是由框架分配和注册。见bindService()实现在android.app.ContextImpl:
public boolean bindService(Intent service, ServiceConnection conn, int flags, int userHandle) {
IServiceConnection sd;
if (conn == null) {
throw new IllegalArgumentException("connection is null");
}
if (mPackageInfo != null) {
// A new ServiceDispatcher will be created and registered along with
// ServiceConnection in LoadedApk.mService for your application context.
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
mMainThread.getHandler(), flags);
} else {
throw new RuntimeException("Not supported in system context");
}
try {
... ...
return res != 0;
} catch (RemoteException e) {
return false;
}
}
你应该总是解除绑定的服务,当你用它做,通过the official dev guide的建议,作为一个良好的编程方式:
的ServiceConnectionLeaked提高(例如,当您的应用程序退出),发现有未注册ServiceConnection,然后该框架将尝试为您解除绑定。见removeContextRegistrations()实现在android.app.LoadedApk:
public void removeContextRegistrations(Context context,
String who, String what) {
final boolean reportRegistrationLeaks = StrictMode.vmRegistrationLeaksEnabled();
... ...
//Slog.i(TAG, "Receiver registrations: " + mReceivers);
HashMap<ServiceConnection, LoadedApk.ServiceDispatcher> smap =
mServices.remove(context);
if (smap != null) {
Iterator<LoadedApk.ServiceDispatcher> it = smap.values().iterator();
while (it.hasNext()) {
LoadedApk.ServiceDispatcher sd = it.next();
ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
what + " " + who + " has leaked ServiceConnection "
+ sd.getServiceConnection() + " that was originally bound here");
leak.setStackTrace(sd.getLocation().getStackTrace());
Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
if (reportRegistrationLeaks) {
StrictMode.onServiceConnectionLeaked(leak);
}
try {
ActivityManagerNative.getDefault().unbindService(
sd.getIServiceConnection());
} catch (RemoteException e) {
// system crashed, nothing we can do
}
sd.doForget();
}
}
mUnboundServices.remove(context);
//Slog.i(TAG, "Service registrations: " + mServices);
}
感谢您的答复,但它仍然是不符合的样品是一致的(例如RemoteService在ApiDemos的确也只有解除绑定,如果'onServiceConnected()'叫)。但是,既然在你的帮助下,我现在可以看到,即使是高层次的描述似乎也允许这样的解释,我会接受答案。 – Stephan