Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restart a thread in java/Android from a button?

I have a thread in java/Android like this:

Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        update_i();
    }
};



@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    Thread myThread = new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    handler.sendMessage(handler.obtainMessage());
                    Thread.sleep(timer);
                } catch (Throwable t) {
                }
            }
        }
    });

    myThread.start();
}

The thread works fine when I run my application. But I want to start/restart the thread with a button.

Button.OnClickListener StartButtonOnClickListener = new Button.OnClickListener() {
    @Override
    public void onClick(View v) {

        //start/restart the thread
    }
};

If I copy the thread into the button I just make a new thread every time the user clicks on the button. I want to run the thread when the user first time click on the button, "kill it" and start from the beginning if the user click on the button a second time (I don’t want to start a second thread).

like image 814
Martin Avatar asked Dec 03 '22 04:12

Martin


2 Answers

I think that Colin is wright you can´t just restart you need to make a new instance, and the interrupt function will stop the running thread if it is still running.

I recommend you make an inner class, instand of an inline implementation, it will make it easier to understand.

if(myThread.isAlive()){
    myThread.interrupt(); 
}
myThread = new MyThread();
myThread.start();

hope this helps

like image 59
mklfarha Avatar answered Dec 23 '22 08:12

mklfarha


You can't restart a Thread.

From the documentation :

Throws IllegalThreadStateException  
    if the Thread has been started before

You can kill the previous thread, but in the end you will have to create a second instance of your thread.


Resources :

  • Javadoc Android - Thread.start()
like image 43
Colin Hebert Avatar answered Dec 23 '22 08:12

Colin Hebert