简体   繁体   中英

AsyncTask randomly stops

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.

PS 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.

PPS

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM