0

I have this thread:

myThread = new Thread(new Runnable() {
                    public void run() {

                        ServerSocket ss = null;

                        while (!end) {

                            final String incomingMsg;
                            try {
                                ss = new ServerSocket(2201);
                                ss.setSoTimeout(15000);
.. some code ...
    }
                });
                myThread.start();

Now i need to stop this with button but nothing work, and i have tried with some code like:

Handler handler= new Handler();
handler.removeCallbacks(myThread);
myThread.interrupt();

But Thread not stopping =(

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
J. Doe Cd
  • 69
  • 9

3 Answers3

1

You can't. Android will automatically stops thread when needed.

What you can do is just stop executing the code inside run() method, Using boolean or something

Paresh P.
  • 6,677
  • 1
  • 14
  • 26
  • 1
    This answer is not correct. Android does nothing to manage the threads you start, however you start them. See my answer for details. – Jeffrey Blattman Nov 17 '17 at 17:05
0

The accepted answer is not correct. Android does nothing to manage the threads you start, however you start them.

Technically speaking, threads cannot be "stopped". They can interrupted. Interrupting a thread just means that a flag is set, which you, in your thread's implementation, need to consider and exit from the run() method. For example,

  Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
      while (!Thread.currentThread().isInterrupted()) {
        // Do stuff
      }
    }
  });

Then you can call t.interrupt() later on to "stop" your thread.

If you ignore the interrupted flag in your thread's implementation, your thread will never stop. For example, if you replaced // Do stuff above with SystemClock.sleep(Integer.MAX_VALUE) the thread will never exit, regardless of it being interrupted.

Many IO operations implemented in the SDK also pay attention to the interrupted flag, which is why you can interrupt a thread that's participating in blocking IO. See InterruptedException.

Jeffrey Blattman
  • 22,176
  • 9
  • 79
  • 134
0

You can use .stop(), but it is very bad practice and it can cause you some troubles. Try to add some boolean inside your .run() (like Wizard said)