Java 返回上一页时android应用程序中的服务连接泄漏
您好,我正在开发一个打卡考勤应用程序,它有一个计时器服务,当用户打卡时运行。我遇到的问题是,当我启动服务,然后按手机上的“后退”按钮返回到上一页时,我发现服务连接泄漏,我不知道如何解决,因为它似乎停止了服务 //onStart-在服务类中启动计时器Java 返回上一页时android应用程序中的服务连接泄漏,java,android,android-service,android-binder,Java,Android,Android Service,Android Binder,您好,我正在开发一个打卡考勤应用程序,它有一个计时器服务,当用户打卡时运行。我遇到的问题是,当我启动服务,然后按手机上的“后退”按钮返回到上一页时,我发现服务连接泄漏,我不知道如何解决,因为它似乎停止了服务 //onStart-在服务类中启动计时器 public int onStartCommand(Intent intent, int flags, int startId) { manager = (NotificationManager)getSystemS
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);
如果Android操作系统销毁
活动
并发现服务连接
仍绑定到正在运行的服务
,您将非常感激,因此您需要在销毁活动
之前解除绑定该服务(返回上一页)
)
解除服务器绑定
unbindService(seamysConnection);
注意:
您应该使用相同的上下文
绑定服务和解除绑定服务。如果您使用getApplicationContext()
绑定服务,那么您也应该使用getApplicationContext.unbindService(..)