一般来说,一个ServiceConnection总是由框架分配和注册,不管bindService()
调用返回true还是false。请参阅android.app.ContextImpl中的 bindService() 实现:
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;
}
}
按照官方开发指南的建议,在完成服务后,您应该始终取消绑定服务,这是一种良好的编程方式:
当框架开始执行最终清理(例如,当您的应用程序退出时)并发现有未注册的 ServiceConnection 时,会引发 ServiceConnectionLeaked,然后框架将尝试为您解除绑定。请参阅android.app.LoadedApk中的 removeContextRegistrations() 实现:
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);
}