Periodically update / reload work

I have one action. OnCreate Activity receives the source (html) of the web page in a string and presents the result (after parsing it a bit) in text form.

I would like the activity to be periodically reloaded / updated to always provide the latest information.

What is the best solution for this?

+6
android
source share
1 answer

First of all ... separate the update logic from your onCreate method. So, for example, you can create updateHTML() .

Then you can use Timer to periodically refresh the page:

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

Please note that I cancel the update task to onPause , in which case the updateHTML method runs every 40 seconds (40,000 milliseconds). Also, make sure you import these two classes: java.util.Timer and java.util.TimerTask .

+27
source share

All Articles