Con questo codice è possibile far partire un timer in una Activity di un app android.
Nel "onCreate", ossia quando parte l'Activity, viene richiamato il timer che verrà ripetuto ogni 100 millisecondi;
nel "runTimer" viene implementata la logica che vogliamo far eseguire dal timer eventualmente bloccandolo con una condizione "if(condition to break)";
in fase di uscita dall'Activity nel "onDestroy" eliminiamo il timer se ancora attivo.
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
public class Main extends Activity {
private Timer myTimer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
timerMethod();
}
}, 0, 100);
//delay: amount of time in milliseconds
//before first execution
//period: amount of time in milliseconds
//between subsequent executions
}
private void timerMethod()
{
this.runOnUiThread(runTimer);
}
private Runnable runTimer = new Runnable() {
public void run() {
/*
do something, write instructions
...
if(condition to break){
myTimer.cancel();
}
*/
}
};
protected void onDestroy() {
if(myTimer!=null)
myTimer.cancel();
super.onDestroy();
}
}