Repeat AsyncTask in background

I create a class which extends from AsyncTask class to get data from sql server with http post, but I need to repeatedly execute this class every X seconds in the background. I mean that if the user opens another activity, the class continues its execution and if it gets a message from the server, it sets this message in dialog in any activity

Upvotes: 0

Views: 187

Answers (2)

from56
from56

Reputation: 4127

Do your AsyncTask an inner static class of your main activity, instantiate AsyncTask only once in onCreate an assign to a static variable, but first check if the variable is null, that will avoid re-instantiate if the Activity is recreated.

The Handler, Runnable or whatever you use for the timing must be static too.

That theoricaly will make your AsyncTask run regardless of whether or not there is an Activity created.

Upvotes: 2

GAGAN BHATIA
GAGAN BHATIA

Reputation: 601

Yor can definitely use a timer for whatever time you want.

         Timer mTimer = new Timer()
          mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                           //Write your Code
                        }
                    });
                }

            }, 0, your desired seconds * 1000);
        }
    });

Upvotes: 1

Related Questions