1

I have custom AsyncTask (ListDownloadTask) that download data and updates UI. I want to make it forever while activity opened. So after AsyncTask did the work it must be scheduled. There are delays between attempts.

I tried to use timer but the problem is new ListDownloadTask().execute(); must be invoked from UI thread.

Now i have timer that generates message for Handler. That seems ugly to me. What is best practice?

@Override
public void onCreate(Bundle savedInstanceState) {
// ...
    new ListDownloadTask().execute();
}

private static final long DOWNLOAD_UPDATES_DELAY = 5 * 1000;
private final Timer mUpdatesDownloaderTimer = new Timer(true);

Handler mDownloadTrigger = new Handler(new Handler.Callback() {
    public boolean handleMessage(Message message) {
        new ListDownloadTask().execute();
        return true;
    }
});

private void scheduleUpdatesDownload() {
    mUpdatesDownloaderTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            mDownloadTrigger.sendEmptyMessage(0);
        }
    }, DOWNLOAD_UPDATES_DELAY);
}

private class ListDownloadTask extends AsyncTask<Long, String, Integer> {
    @Override
    protected void onPostExecute(Integer result) {
        //...
        scheduleUpdatesDownload();
    }
1
  • Thanks for answers. I should use service from very beginning.
    – Dmitry
    Feb 9, 2011 at 7:57

3 Answers 3

0

Check out this example that is kinda similar to what you want to do. It might be better to use a Local Service also though.

0
0

Try Handler.sendEmptyMessageDelayed or Handler.sendEmptyMessageAtTime.

0

Create a service and bind to it in your activity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.