简体   繁体   中英

Looping Async Tasks in Android - whats the good way?

I want to parse Data from a webserver to my android device every few minutes. I already implemented an AsyncTask, which is updating my UI in the OnPostExecute() Method.

I didn't find a good way to repeat the AsyncTask. I tried Handlers, Threads and ExecutorServices...I didn't manage to make the Asynctask repeat after the data has been updated. There are hundreds of threads about this topic and each of them comes to a different result.

My source is returning some IllegalStateException after my Handler tried to restart my runnable.

12-15 21:15:36.909: E/AndroidRuntime(28256): java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)

Source (onCreate() ...) :

....
....

    websitesAsyncTask = new WebsitesAsyncTask();
        mHandler = new Handler();

        refreshWebsitesRunnable = new Runnable() {
            @Override
            public void run() {

                // mHandler.removeCallbacks(refreshWebsitesRunnable);

                if (mThreadExecutor == null || mThreadExecutor.isShutdown()) {
                    mThreadExecutor = Executors.newSingleThreadExecutor();
                }

                // TODO Auto-generated method stub
                Log.d("scheduled task",
                        "---Scheduled Task: Refresh Websites");

                if (websitesAsyncTask.getStatus() != Status.RUNNING) {
                //  websitesAsyncTask.cancel(true);

                    websitesAsyncTask
                            .executeOnExecutor(mThreadExecutor);
                }

                mHandler.postDelayed(refreshWebsitesRunnable, 10000);

            }

        };

        startRepeatingTask();
    }

How do I repeat my Task without blocking the UI and without writing dirty code?

An AsyncTask instance can only be called once. To make a second call, you need to create a new instance.

there is a way and you actualy need one AsyncTask

doInBackground(...){
    while(Condition){
        //do your stuff
        //...

        Thread.sleep(5000)
    }

}

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