我们已经开发了一个Android应用程序,是指在后台的服务。为了实现我们已经使用IntentService
这个后台服务。我们希望应用程序轮询服务器每60 seconds
。所以在IntentService
,服务器在while循环轮询。在while循环的末尾,以便下一次迭代开始仅60秒后,我们已经使用Thread.sleep(60000)
。
但在Logcat
,我看到,有时需要的应用程序超过5分钟醒来(出来睡眠,并开始下一次迭代)。这是从来没有1 minute
因为我们希望它是。
,这是什么原因呢?如果后台服务以不同的方式来实现?
Problem2
Android的一段时间后杀死这个后台进程(意向服务)。不能什么时候说。但有时其小时,甚至数天前的后台服务就会被杀死。我将不胜感激,如果你能告诉我这样做的原因。因为服务是注定不会被杀死。这意味着它们是只要我们希望它在后台运行。
代码:
@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
。为什么该服务就会被杀死?
你可以尝试用JobService在后台运行的jobscheduler实现其更高版本的Android O.推荐
Android是大约杀死了长时间运行的服务还不错。我发现CommonsWare的WakefulIntentService有用在我的应用程序:https://github.com/commonsguy/cwac-wakeful
它可以让你当你试图通过睡眠办指定的时间间隔。
It could be probably for two reasons..
temp==true
工作long delays
高达6 seconds
。在情况下,系统正在为一个庞大的数据库,每个查询之间创建long delays
将增加对系统内存。当应用程序的内存使用情况变得如此巨大,在system memory gets low
,系统必须terminate the process
..
解决方案的问题..Alarm Manager
上述替换使用报警管理特定的时间间隔后,取消系统服务。START_REDELIVER_INTENT
。这是您最后一次工作的意图回到应用程序终止后。它的使用情况,研究https://developer.android.com/reference/android/app/Service.html#START_REDELIVER_INTENT