【发布时间】:2012-01-10 14:58:16
【问题描述】:
我目前在我的应用中使用 2 项服务:
1:LocationService,主要是尝试本地化用户,目的是仅在应用处于前台时保持活动状态。
2:XmppService,它初始化与 xmpp 服务器的连接、接收消息、发送消息、注销...并旨在保持活动状态直到用户注销。
我已经阅读了很多文档,但我无法说清楚。
当我尝试存储 LocationServiceBinder 的引用时,我遇到了泄漏,它用于调用我的服务函数(使用 AIDL 接口 )。 Xmpp 也一样。当我解除绑定时,有时会出现 ANR(这似乎与我的绑定/解除绑定异常完成的事实有关,onResume、onRestart ...)。
所有系统都在工作,但我确信这不是正确的做法,我很乐意跟随有经验的人回到部队的右侧! :)
干杯
更新
我的位置服务在应用启动时绑定,以尽可能快地获取用户的位置:
if(callConnectService == null) {
callConnectService = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
locationServiceBinder = LocationServiceBinder.Stub.asInterface(binder);
try {
global.setLocationBinder(locationServiceBinder);
global.getLocationBinder().startLocationListener();
} catch (Exception e){
Log.e(TAG, "Service binder ERROR");
}
}
public void onServiceDisconnected(ComponentName name) {
locationServiceBinder = null;
}
};
}
/* Launch Service */
aimConServ = new Intent(this, LocationService.class);
boolean bound = bindService(aimConServ,callConnectService,BIND_AUTO_CREATE);
我的 Xmpp 服务在用户登录时启动:
callConnectService = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
try {
Log.d(TAG, "[XMPP_INIT] Complete.");
global.setServiceBinder(ConnectionServiceBinder.Stub.asInterface(binder));
//Connect to XMPP chat
global.getServiceBinder().connect();
} catch (Exception e){
Log.e(TAG, "Service binder ERROR ");
e.printStackTrace();
}
}
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "Service binder disconnection ");
}
};
/* Launch Service */
Intent aimConServ = new Intent(MMWelcomeProfile.this, XmppService.class);
bound = bindService(aimConServ,callConnectService,Context.BIND_AUTO_CREATE);
并在每个 Activity 上取消绑定:
if (callConnectService != null){
unbindService(callConnectService);
callConnectService = null;
}
【问题讨论】:
-
发布一些代码 sn-p 在您有问题的活动中的绑定/取消绑定服务可能会帮助其他人找到您的问题。
-
已更新,只是添加了一些代码
标签: android service geolocation xmpp