我们已经开发了一个Android应用程序,涉及的后台服务。为了实现我们用这个后台服务 IntentService 。我们希望应用程序向服务器轮询每个60秒。所以在 IntentService ,服务器轮询在一个while循环。在while循环的最后,我们使用了视频下载(60000),以便下一次迭代只有60秒后开始。但在 logcat的,我看到,有时需要的应用程序超过5分钟醒来(走出睡眠,并开始下一次迭代)。这是从来没有1分钟,因为我们希望它是。
We have developed an Android Application which involves a service in the background. To implement this background service we have used IntentService. We want the application to poll the server every 60 seconds. So in the IntentService, the server is polled in a while loop. At the end of the while loop we have used Thread.sleep(60000) so that the next iteration starts only after 60 seconds. But in the Logcat, I see that sometimes it takes the application more than 5 minutes to wake up (come out of that sleep and start the next iteration). It is never 1 minute as we want it to be.
,这是什么原因呢?如果后台服务以不同的方式来实现?
What is the reason for this? Should background Services be implemented in a different way?
Problem2
在Android的某个时候杀死这个后台进程(意向服务)。不能完全说的时候。但有时它的小时甚至数天前,后台服务就会被杀死。我想AP preciate它,如果你能告诉我这样做的原因。因为服务是注定不会被杀死。这意味着它们是在后台,只要我们希望它运行。
Android kills this background process (intent service) after sometime. Can't exactly say when. But sometimes its hours and sometimes days before the background service gets killed. I would appreciate it if you would tell me the reason for this. Because Services are not meant to be killed. They are meant to run in background as long as we want it to.
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; } } }
但每当服务被杀害,它发生时,这个过程是睡着了。最后的日志读取 - 睡觉:睡觉。为什么该服务就会被杀死?
But whenever the service is killed, it happens when the the process is asleep. The last log reads - Sleeping : Sleeping. Why does the service gets killed?
推荐答案主要的问题是,我们不能说
The main problem is that we cannot say
服务的目的不是被杀死。这意味着它们是在后台,只要我们希望它运行。
Services are not meant to be killed. They are meant to run in background as long as we want it to.
基本上,这是不正确的。系统仍然可以终止在低内存和其他可能的情况下的服务。 有2种方法来解决这个问题:
Basically, that is not true. System still can terminate the service in low memory and possibly other situations. There are 2 ways to overcome this:
好运气
更多推荐
在Android的后台服务亡
发布评论