Skip to content

Instantly share code, notes, and snippets.

@chancyWu
Created July 3, 2014 03:51
Show Gist options
  • Save chancyWu/9495c1b728088dc2d1d2 to your computer and use it in GitHub Desktop.
Save chancyWu/9495c1b728088dc2d1d2 to your computer and use it in GitHub Desktop.
use Handler to execute the function repeatedly & stop in Android
private boolean keepLooping = true;
private static final int DELAY = 1000 * 5;
final Handler printHandler = new Handler();
Runnable printStuff = new Runnable(){
@Override
public void run(){
System.out.println("done");
if(keepLooping)
printHandler.postDelayed(this, DELAY);
}
}
//wherever you want to start your printing
printHandler.postDelayed(printStuff, DELAY);
keepLooping = true;
//when back is pressed or app is stopped
keepLooping = false;
printHandler.removeCallbacks(printStuff);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment