您好我正在开发一个时钟进出的考勤应用程序,该应用程序具有在用户计时时运行的计时器服务。我遇到的问题是当我启动服务然后按电话上的后退按钮返回到上一页我得到服务连接泄漏,我不知道如何解决这个问题,因为它似乎停止了服务。
// onStart - 在服务类
中启动计时器 public int onStartCommand(Intent intent, int flags, int startId) {
manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
displayNotification("Clock in timer started");
clockTask = new TimerTask() {
public void run() {
seconds++;
}
};
startCounter();
return START_STICKY;
}
//onDestroy to stop the service and counter
public void onDestroy() {
super.onDestroy();
long mins = seconds/60;
seconds%=60;
long hours = mins/60;
mins%=60;
stopCounter();
// manager.cancel(R.string.notification);
displayNotification("Clocked out after : "+""+hours+":"+mins+":"+String.format("%02d",seconds));
//seconds = 0L;
}
//我如何绑定活动类中的意图
Intent i = new Intent(this, StartTimerService.class);
bindService(i, seamysConnection, Context.BIND_AUTO_CREATE);
非常感谢任何帮助
答案 0 :(得分:1)
Activity
并发现A ServiceConnection
仍然绑定到正在运行的Service
时会发生这种情况,因此您需要先Unbind
该服务然后销毁Activity
1}}(返回上一页
)
取消绑定服务器
unbindService(seamysConnection);
注意:强>
您应该使用相同的context
来绑定服务并取消绑定服务。如果您使用getApplicationContext()
绑定服务,那么您还应该使用getApplicationContext.unbindService(..)