Skip to content

Instantly share code, notes, and snippets.

@j-fliegenschmidt
Created September 7, 2013 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j-fliegenschmidt/6479668 to your computer and use it in GitHub Desktop.
Save j-fliegenschmidt/6479668 to your computer and use it in GitHub Desktop.
A simple activity that has all it needs to be regularly updated while on screen.
package com.example.uiupdatetest;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv;
Timer updateTimer;
int counter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textview);
}
@Override
protected void onStart() {
super.onStart();
updateTimer = new Timer();
updateTimer.schedule(new updateTask(new Handler(), this), 0, 1000);
}
@Override
protected void onStop() {
super.onStop();
updateTimer.cancel();
updateTimer.purge();
}
public void update() {
// This is where the UI calls go
tv.setText(String.valueOf(++counter));
}
private class updateTask extends TimerTask {
Handler handler;
MainActivity ref;
public updateTask(Handler handler, MainActivity ref) {
super();
this.handler = handler;
this.ref = ref;
}
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
ref.update();
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment