【发布时间】:2014-06-13 03:03:14
【问题描述】:
我的活动尝试启动并绑定一个应该独立运行的服务。此服务打开 GPS。
onCreate 调用 getApplicationContext.StartService,而 onResume 调用 getApplicationContext.BindService。 OnPause 调用getApplicationContext.unbindService,尽管它似乎从未正常运行(服务连接从未记录取消绑定,尽管在我以类似方式处理绑定时会记录绑定)。
不幸的是,当我打开我的“最近”列表并将活动滑开时,服务会停止,然后几乎立即重新启动,从而断开 GPS 连接。什么会导致这种行为?
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
// Start up the service
Intent intent = new Intent(getApplicationContext(), LockService.class);
getApplicationContext().bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onPause() {
super.onPause();
Log.i(tag, "onPause");
if (isBound) {
getApplicationContext().unbindService(myConnection);
}
}
...
// Bound service stuff
LockService myService;
boolean isBound = false;
private ServiceConnection myConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
LockBinder binder = (LockBinder) service;
myService = binder.getService();
isBound = true;
final boolean status = myService.getStatus();
Log.i(tag, "service bound");
}
@Override
public void onServiceDisconnected(ComponentName className) {
isBound = false;
Log.i(tag, "service unbound");
}
};
编辑:我检查了这个答案,但这只是阻止服务立即重新启动(它仍然挂起,重新打开活动会重新初始化它):
Android onCreate Service called when Activity onDestroy called
编辑 2: 我对这个答案的希望有点过头了。它似乎也无法解决任何问题。
How to force the onServiceDisconnected() get called?
编辑 3:这可能是奇巧的东西。
【问题讨论】: