我们开发了一个 Android 应用程序,其中涉及后台服务。为了实现这个后台服务,我们使用了IntentService
。我们希望应用程序每隔一段时间轮询一次服务器60 seconds
。所以在IntentService
,在 while 循环中轮询服务器。在 while 循环的末尾我们使用了Thread.sleep(60000)
以便下一次迭代仅在 60 秒后开始。
但在Logcat
,我发现有时应用程序需要 5 分钟以上才能唤醒(从睡眠中醒来并开始下一次迭代)。从来都不是1 minute
正如我们所希望的那样。
这是什么原因呢?后台服务是否应该以不同的方式实现?
Problem2
Android 会在一段时间后杀死这个后台进程(意图服务)。不能具体说是什么时候。但有时后台服务会被杀死几个小时甚至几天。如果您能告诉我原因,我将不胜感激。因为服务不应该被杀死。只要我们愿意,它们就会在后台运行。
Code :
@Override
protected void onHandleIntent(Intent intent) {
boolean temp=true;
while(temp==true) {
try {
//connect to the server
//get the data and store it in the sqlite data base
}
catch(Exception e) {
Log.v("Exception", "in while loop : "+e.toString());
}
//Sleep for 60 seconds
Log.v("Sleeping", "Sleeping");
Thread.sleep(60000);
Log.v("Woke up", "Woke up");
//After this a value is extracted from a table
final Cursor cur=db.query("run_in_bg", null, null, null, null, null, null);
cur.moveToLast();
String present_value=cur.getString(0);
if(present_value==null) {
//Do nothing, let the while loop continue
}
else if( present_value.equals("false") || present_value.equals("False") ) {
//break out of the while loop
db.close();
temp=false;
Log.v("run_in_bg", "false");
Log.v("run_in_bg", "exiting while loop");
break;
}
}
}
但是,每当服务被终止时,都会发生在进程处于睡眠状态时。最后一条日志写着——Sleeping : Sleeping
。为什么服务会被杀死?