我需要让RSS Feed阅读器每隔10分钟检查一次feed,以查找新帖子,然后对它们进行解析(如果有新帖子)。我还需要大约每分钟更新一次UI。

我已经阅读并听到了来自不同来源的不同观点。我目前的理解是,我可以使用ScheduledThreadPoolExecutor来创建两个调度线程,其中一个需要Handler来更新UI。我不确定这些类或TimerTask的最有效使用方法是什么。

对于这些子类的子类,我也不确定。一位 friend 建议将TimerTask扩展为我的FeedParser类的内部类,以使其更简单。但是,要以这种方式实现它,我必须对run()使用TimerTask方法而不覆盖它,这意味着我不能简单地使用需要运行的函数所需的参数。

简而言之,为此安排任务的最佳方法是什么,我将在哪里实现这些方法?

最佳答案

我更喜欢使用ScheduledThreadPoolExecutor。通常,如果我正确理解您的要求,那么所有这些都可以在您的 Activity 中实现,不需要TimerTask和Handler,请参见下面的示例代码:

public class MyActivity extends Activity {
  private ScheduledExecutorService scheduleTaskExecutor;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    scheduleTaskExecutor= Executors.newScheduledThreadPool(5);

    // This schedule a task to run every 10 minutes:
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
      public void run() {
        // Parsing RSS feed:
        myFeedParser.doSomething();

        // If you need update UI, simply do this:
        runOnUiThread(new Runnable() {
          public void run() {
            // update your UI component here.
            myTextView.setText("refreshed");
          }
        });
      }
    }, 0, 10, TimeUnit.MINUTES);
  } // end of onCreate()
}

请记住在Activity.onDestroy()中正确完成/关闭您的可运行任务,希望对您有所帮助。

10-07 19:14
查看更多