I am using a handler in the following program and I want to stop it when i=5 but the handler doesn't stop and run continuously.
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
handler = new Handler();
runnable = new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(), "Handler is working", Toast.LENGTH_LONG).show();
System.out.print("Handler is working");
if(i==5){
//Thread.currentThread().interrupt();
handler.removeCallbacks(runnable);
System.out.print("ok");
Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
}
i++;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(runnable, 5000);
//return;
}
});
handler.removeCallbacks(runnable);
developer.android.com/reference/android/os/Handler.html – Vaud