Android:如何在另一个任务(TimerTask)中运行任务

时间:2013-07-07 16:49:55

标签: android android-asynctask timertask thread-exceptions

我有以下代码:

//Task that runs in background thread and posts results
private class NewsWorkerTask extends AsyncTask<Void, Void, List<NewsData>> {

    @Override
    protected void onPreExecute() { 
    }

    @Override
    protected List<NewsData> doInBackground(Void... params) {           

        if (NewsDataProvider==null || NewsDataProvider.PageNumber ==0)
        {
            //Get New Data and initialize
            NewsDataProvider = new NewsProvider(getActivity());
            return NewsDataProvider.GetTopNews();
        }
        else
        {
            List<NewsData> tempDataList = NewsDataProvider.GetTopNews();

            // Merge new page
            for (NewsData item : tempDataList) {

                TopNewsDataList.add(item);
            }
        }

        return null;
    }

    /*
     * The system calls this to perform work in the UI thread and delivers
     * the result from doInBackground()
     */
    @Override
    protected void onPostExecute(List<NewsData> data) {

        final List<NewsData> tempDataList = data;

        //Declare the timer
        Timer t = new Timer();

        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                //Called each time when 1000 milliseconds (1 second) (the period parameter)
                if (tempDataList != null && tempDataList.size() > 0) {

                    if (tempDataList.size() == 1) {
                        TextView txtNewsTitle = (TextView)getView().findViewById(R.id.txtNewsTitle);
                        TextView txtNewsDate = (TextView)getView().findViewById(R.id.txtNewsDate);
                        txtNewsTitle.setText(tempDataList.get(0).DESCRIPTION);
                        txtNewsDate.setText(tempDataList.get(0).NEWS_DATE);
                    }
                    else {
                        TextView txtNewsTitle = (TextView)getView().findViewById(R.id.txtNewsTitle);
                        TextView txtNewsDate = (TextView)getView().findViewById(R.id.txtNewsDate);
                        txtNewsTitle.setText(tempDataList.get(newsIndex).DESCRIPTION);
                        txtNewsDate.setText(tempDataList.get(newsIndex).NEWS_DATE);

                        newsIndex++;

                        if (newsIndex == (tempDataList.size() - 1)) {
                            newsIndex = 0;
                        }
                    }
                }
            }
        },
        //Set how long before to start calling the TimerTask (in milliseconds)
        0,
        //Set the amount of time between each execution (in milliseconds)
        5000);
    }   
}

正如您所看到 TimerTask NewsWorkerTask onPostExecute 方法中运行

执行此操作时出现以下错误:

致命异常:Timer-0 android.view.ViewRootImpl $ CalledFromWrongThreadException 只有创建视图层次结构的原始线程才能触及其视图。

我把计时器放在onPostExecute中的原因是因为我需要在获取数据时执行计时器(GetTopNews()) GetTopNews基本上给了我十大最新消息,我想在一个盒子里面显示它们,每隔5秒就会切换到下一条消息。

1 个答案:

答案 0 :(得分:1)

尝试使用

    yourview.post(new Runnable() {
        public void run() {
//change your defined view here
    }
    });

在timertask内部并更新上面函数内的视图!