Created
September 7, 2013 21:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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