我有一项 Activity 。 OnCreate Activity 将网页的源 (html) 获取到一个字符串,并在 TextView 中显示结果(在稍微解析之后)。
我希望 Activity 定期重新加载/刷新以始终显示最新信息。
最好的解决方案是什么?
最佳答案
首先...将更新逻辑与 onCreate
方法分开。因此,例如,您可以创建一个 updateHTML()
。
然后,您可以使用 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();
}
}
请注意,我在 onPause
取消了更新任务,在这种情况下,updateHTML
方法每 40 秒(40000 毫秒)执行一次。此外,确保导入这两个类:java.util.Timer
和 java.util.TimerTask
。
关于android - 定期刷新/重新加载 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3701106/