简体   繁体   English

在Android中循环异步任务 - 最好的方法是什么?

[英]Looping Async Tasks in Android - whats the good way?

I want to parse Data from a webserver to my android device every few minutes. 我想每隔几分钟从网络服务器解析数据到我的Android设备。 I already implemented an AsyncTask, which is updating my UI in the OnPostExecute() Method. 我已经实现了一个AsyncTask,它正在OnPostExecute()方法中更新我的UI。

I didn't find a good way to repeat the AsyncTask. 我没有找到重复AsyncTask的好方法。 I tried Handlers, Threads and ExecutorServices...I didn't manage to make the Asynctask repeat after the data has been updated. 我尝试过Handler,Threads和ExecutorServices ...我没有设法在数据更新后重复Asynctask。 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. 我的源代码在Handler尝试重新启动runnable后返回一些IllegalStateException。

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() ...) : 来源(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? 如何在不阻止UI且不编写脏代码的情况下重复我的任务?

An AsyncTask instance can only be called once. AsyncTask实例只能调用一次。 To make a second call, you need to create a new instance. 要进行第二次调用,您需要创建一个新实例。

there is a way and you actualy need one AsyncTask 有一种方法,你需要一个AsyncTask

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

        Thread.sleep(5000)
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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