1

I have a pull based app that has to pull from the Server every 15 seconds. For that I used a normal AsyncTask, my code basically looks like this:

protected Void doInBackground(Context... arg0) {
   while (true && this.pull_on ) {
     pull_data();
     TimeUnit.SECONDS.sleep(15)
};

Now I have the massive Problem that, the app just stops pulling out of the blue. No exeptions, the Status of the AsyncTask is 'running' the 'pull_on' variable is set to 'true' but it just stops pulling.

I can not reproduce this, it just happens sometimes, I can work perfectly for a long time and then it just stops.

Does anybody have an idea how this can happen?

Should I refactor and implement this with a timer?

Also what benefit would using a Service have over what I do know? Battery-power is not an issue.

Thanks for your help.

P.S. I should add that sometimes I start Activitys form the AsyncTask. Like this 'ApplicationManager.getCurrentActivity().startActivity( myIntent )' but I does not seam to be a Problem.

P.P.S.

Timer seams to be to limited for what I want to use, I do want to do something every 15 seconds but in some special case I want to stop the the pinging and then restart it again. The amount of hacking for that seams to be more work then just doing it with a AsyncTask.

4

1 回答 1

1

这是一个糟糕的设计。您不希望每 15 秒在后台进行一次无限循环。当应用程序被推到后台时,这会耗尽电池电量,这是主要问题之一。

一种正确的方法是设置警报并对此做出反应。计时器也不是一个坏选择。

我建议您考虑将其转移到服务中,这就是它的样子

Service是一个应用程序组件,可以在后台执行长时间运行的操作,并且不提供用户界面

它讨论了长时间运行的操作,但将经常性操作移至服务也很有意义。

有关服务的官方文档在这里:http: //developer.android.com/guide/components/services.html

于 2012-12-18T15:31:02.737 回答