Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly interrupt a thread in android

In my application I have a button and when it gets clicked I start a new thread and change the text of button. If I press the button again it will start changing its text faster.

I would like to interrupt the thread when the button is pressed in the second time. What's the correct way to do it?

public class TestActivity extends Activity {

 Button btn;
 int i = 0;

 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     btn = (Button)findViewById(R.id.btn);
     btn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           runThread();
       }
     });
 }

private void runThread() {
    new Thread() {
      public void run() {
          while (i++ < 1000) {
              try {
                  runOnUiThread(new Runnable() {

                      @Override
                      public void run() {
                          btn.setText("#" + i);
                      }
                  });
                  Thread.sleep(300);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
    }.start();
}
like image 360
user3764893 Avatar asked Jul 09 '14 12:07

user3764893


2 Answers

In this case, just keep a reference to your thread and use Thread.interrupt():

private Thread runThread() {

return new Thread() {
  public void run() {
      while (i++ < 1000) {
          try {
              runOnUiThread(new Runnable() {

                  @Override
                  public void run() {
                      btn.setText("#" + i);
                  }
              });
              Thread.sleep(300);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
}

Then:

 btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       if (myThread != null) myThread.interrupt();
       myThread = runThread();
       myThread.start();
   }
 });

Read this post for more info and options:

How to properly stop the Thread in Java?

like image 188
Jim Avatar answered Sep 22 '22 03:09

Jim


In my opinion, the best way would be using a variable to control this.

Something like:

while(i++ < 1000 && keepRunning)

I see that as a good solution because it cant cause unexpected behavior, as you are sure the exactly moment your thread would exit.

extra--

As a suggestion, I also would recommend you to set your thread non-Damon (setDaemon(false)) because it makes layout changes

Also it is a good practice to give thread a name (setName()) to make it easy on debugging.

like image 31
Pozzo Apps Avatar answered Sep 23 '22 03:09

Pozzo Apps