I eventually managed to get my other post sorted; to create a way to update the GUI every second or so. So my runnable runs fine but now I’ve added a button to the GUI which is meant to stop the runnable. But how do you do it?
I’ve tried this code:
// Button to stop the runnable
stop = ( Button ) findViewById( R.id.stop );
stop.setOnClickListener( new View.OnClickListener()
{
@Override
public void onClick(View v)
{
handler.removeCallbacksAndMessages( timerTask.class );
}
});
I implement Runnable in order to use it, therefore I don’t create a new Thread manually and add a run() method to it. So how do you do it?
Thanks
You can’t just murderize the thread. What you’ll need to do is add a method to your
Runnableobject implementation that acknowledges a request to stop. That method then flips a condition that causes yourRunnable.run()method to exit.So in your
onClick(View v)implementation for your stop button, you would callyourClassInstance.stop(). That breaks the loop, therun()method ends, and the thread is cleaned up.