Reputation: 5881
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.
Upvotes: 1
Views: 131
Reputation: 3996
That is a terrible design. You do not want to have an infinite loop on the background every 15 seconds. That will drain battery when the app is pushed to the background, as one of the main problems.
One proper way to do it is to have an Alarm and react to that. A timer is not a bad option either.
I suggest you look into moving this to a service, which is what it looks like
A Service is an application component that can perform long-running operations in the background and does not provide a user interface
It talks about long-running operations, but recurrent operations also make sense to be moved to a service.
Official documentation on Services is here: http://developer.android.com/guide/components/services.html
Upvotes: 1