There is an activity with three buttons: Create a new thread, start a stream and stop. My problem is that the thread does not stop after calling the interrupt method (the call is made by pressing the stop button). I added the isInterrupted() check to the isInterrupted() , but this method for some reason always returns false . Here is my code:

 private View.OnClickListener listener = new View.OnClickListener() { @SuppressLint("HandlerLeak") @Override public void onClick(View v) { switch (v.getId()){ case R.id.create_button: thread = new Thread(new Runnable() { @Override public void run() { int i; for (i = 0; i<10;i++){ final int finalI = i; new Handler().postDelayed(new Runnable() { @Override public void run() { textCounter.post(new Runnable() { @Override public void run() { textCounter.setText(String.valueOf(finalI)); } }); } }, 500*i); if (thread.isInterrupted()){ Log.i(getClass().getSimpleName(), "Thread is interrupted"); return; } } new Handler().postDelayed(new Runnable() { @SuppressLint("SetTextI18n") @Override public void run() { textCounter.setText("Done!"); } },(i+1)*500); } }); break; case R.id.start_button: thread.run(); break; case R.id.cancel_button: thread.interrupt(); Log.i(getClass().getSimpleName(), "Cancel Button clicked"); break; } } }; 

Therefore, the question is: why the flow is not interrupted and how to fix it?

  • one
    Well, as long as there is no thread as such, run it thread.start () and not run () - Serodv

0