[英]Service stops when app goes to background in android
I have been using handler inside service class, the handler is responsible for sending location every 5 seconds via socket.我一直在服务 class 中使用处理程序,处理程序负责通过套接字每 5 秒发送一次位置。 I cancel timer in
onDestroy
method.我在
onDestroy
方法中取消计时器。 when app goes to background the service gets stopped after 1 minutes.当应用程序进入后台时,服务会在 1 分钟后停止。
public Runnable mn_Runnable12 = new Runnable() {
public void run() {
gps = new GPSTracker(LocationService.this);
if (gps.canGetLocation()) {
latString = Double.toString(gps.getLatitude()); // Live
logString = Double.toString(gps.getLongitude());
connection= MyApplication.getInstance().getConnection();
if (connection!=null&&connection.isConnected()) {
sendLocation();
}
}
}
};
this is inside onCreate()
of service.这是在服务的
onCreate()
里面。
T.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
mHandler12.postDelayed(mn_Runnable12, 5000);
}
},
5000,
5000);
I try to stop the handler in onDestroy
method of service, service gets topped but the handler still running.我尝试在服务的
onDestroy
方法中停止处理程序,服务被置顶但处理程序仍在运行。
@Override
public void onDestroy() {
System.out.println("Location Service Detaroy-----");
// T.cancel();
// T.purge();
if(mHandler12!=null){
mHandler12.removeCallbacksAndMessages(null);
}if(mHandler10!=null){
mHandler10.removeCallbacksAndMessages(null);
}
}
I have been using handler inside service class, the handler is responsible for sending location every 5 seconds via socket.我一直在服务 class 中使用处理程序,处理程序负责通过套接字每 5 秒发送一次位置。 I cancel timer in
onDestroy
method.我在
onDestroy
方法中取消计时器。 when app goes to background the service gets stopped after 1 minutes.当应用程序进入后台时,服务会在 1 分钟后停止。
public Runnable mn_Runnable12 = new Runnable() {
public void run() {
gps = new GPSTracker(LocationService.this);
if (gps.canGetLocation()) {
latString = Double.toString(gps.getLatitude()); // Live
logString = Double.toString(gps.getLongitude());
connection= MyApplication.getInstance().getConnection();
if (connection!=null&&connection.isConnected()) {
sendLocation();
}
}
}
};
this is inside onCreate()
of service.这是在服务的
onCreate()
里面。
T.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
mHandler12.postDelayed(mn_Runnable12, 5000);
}
},
5000,
5000);
I try to stop the handler in onDestroy
method of service, service gets topped but the handler still running.我尝试在服务的
onDestroy
方法中停止处理程序,服务被置顶但处理程序仍在运行。
@Override
public void onDestroy() {
System.out.println("Location Service Detaroy-----");
// T.cancel();
// T.purge();
if(mHandler12!=null){
mHandler12.removeCallbacksAndMessages(null);
}if(mHandler10!=null){
mHandler10.removeCallbacksAndMessages(null);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.