Where do I create and use ScheduledThreadPoolExecutor, TimerTask, or Handler?

前端 未结 1 1607
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 03:26

I need to make my RSS Feed reader check the feed every 10 minutes for new posts, and then parse them if there are new ones. I also need to update the UI about every minute.<

相关标签:
1条回答
  • 2020-11-27 03:51

    I prefer to use ScheduledThreadPoolExecutor. Generally, if I understand your requirements correctly, all these can be implemented in your activity, TimerTask and Handler are not needed, see sample code below:

    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()
    }
    

    Remember to finish/close your runnable task properly in Activity.onDestroy(), hope that help.

    0 讨论(0)
提交回复
热议问题