Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodically refresh/reload activity

Tags:

android

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.

I would like the activity to reload/refresh periodically to always present the latest information.

What is the best solution for this?

like image 387
Raffe Avatar asked Sep 13 '10 13:09

Raffe


1 Answers

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

Then, you can use a Timer in order to update the page periodically:

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). Also, make sure you import these two classes: java.util.Timer and java.util.TimerTask.

like image 76
Cristian Avatar answered Oct 20 '22 20:10

Cristian