简体   繁体   English

定期刷新/重新加载活动

[英]Periodically refresh/reload activity

I have one activity. 我有一项活动。 OnCreate the activity gets the source (html) of a web page to a string and presents the result (after parsing it a bit) in a textview. OnCreate活动将网页的源(html)获取为字符串,并在textview中显示结果(稍微解析一下)。

I would like the activity to reload/refresh periodically to always present the latest information. 我希望活动定期重新加载/刷新以始终显示最新信息。

What is the best solution for this? 什么是最好的解决方案?

First of all... separate the updating logic from your onCreate method. 首先......将更新逻辑与onCreate方法分开。 So, for instance, you can create an updateHTML() . 因此,例如,您可以创建updateHTML()

Then, you can use a Timer in order to update the page periodically: 然后,您可以使用Timer来定期更新页面:

public class YourActivity extends Activity {

 private Timer autoUpdate;

 public void onCreate(Bundle b){
  super.onCreate(b);
  // whatever you have here
 }

 @Override
 public void onResume() {
  super.onResume();
  autoUpdate = new Timer();
  autoUpdate.schedule(new TimerTask() {
   @Override
   public void run() {
    runOnUiThread(new Runnable() {
     public void run() {
      updateHTML();
     }
    });
   }
  }, 0, 40000); // updates each 40 secs
 }

 private void updateHTML(){
  // your logic here
 }

 @Override
 public void onPause() {
  autoUpdate.cancel();
  super.onPause();
 }
}

Notice that I'm canceling the updating task on onPause , and that in this case the updateHTML method is executed each 40 secs (40000 milliseconds). 请注意,我正在取消onPause上的更新任务,并且在这种情况下, updateHTML方法每40秒(40000毫秒)执行一次。 Also, make sure you import these two classes: java.util.Timer and java.util.TimerTask . 另外,请确保导入这两个类: java.util.Timerjava.util.TimerTask

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

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