我目前在我的应用程序中使用两个服务:
1: LocationService,基本上是试图将用户本地化,目的是只在应用程序处于前台时才能存活。
2: XmppService,它包含与xmpp服务器的连接,接收消息,发送消息,注销.并希望在用户注销之前保持存活。
我已经读了很多文档,但是我不能说清楚。
当我试图存储用于调用我的服务函数(使用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 =新的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);并解除对每项活动的约束:
if (callConnectService != null){
unbindService(callConnectService);
callConnectService = null;
}发布于 2012-12-27 16:13:16
如果绑定到活动中的服务,也需要解除绑定:
@Override
protected void onResume() {
Log.d("activity", "onResume");
if (locationServiceBinder == null) {
doBindLocationService();
}
super.onResume();
}
@Override
protected void onPause() {
Log.d("activity", "onPause");
if (locationServiceBinder != null) {
unbindService(callConnectService);
locationServiceBinder = null;
}
super.onPause();
}其中doBindLocationService()
public void doBindLocationService() {
Log.d("doBindService","called");
aimConServ = new Intent(this, LocationService.class);
// Create a new Messenger for the communication back
// From the Service to the Activity
bindService(aimConServ, callConnectService, Context.BIND_AUTO_CREATE);
}您也需要为您的XmppService进行此练习。
https://stackoverflow.com/questions/8341782
复制相似问题