2

How can I stop new Thread(new Runnable()).run

I am new in android development :D, and I need your help :)

I have this code and I would like to stop it after executing

      new Thread(new Runnable() {
         @Override public void run() {
             Log.e("MotionLogger", "SU");
             Log.i(TAG, "click " + Thread.currentThread().toString());

             try {
                 finalCommandLine.writeBytes(command.toString() + '\n');
                 finalCommandLine.writeBytes("exit\n");
                 finalCommandLine.flush();
                 finalCommandLine.close();
                 finalSuShell.waitFor();
             } catch (IOException e1) {
                 e1.printStackTrace();
             } catch (InterruptedException e1) {
                 e1.printStackTrace();
             }
         }

     }).start();

Thanks in advance :)

  • Look into [`Thread.interrupt()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupt()) and [`Thread.isInterrupted()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#isInterrupted()). – JimmyB Sep 21 '17 at 09:34
  • 2
    "I would like to stop it after executing" - The thread terminates automatically once its `run()` method returns. You don't have to do anything for that. – JimmyB Sep 21 '17 at 09:35
  • Stop Runnable Thread https://stackoverflow.com/a/58038337/5788247 – Shomu Feb 05 '20 at 10:35

1 Answers1

1

In your case you can use thread.interrupt

Or Create Handler like this if you want to run on UI thread

Handler handler= new Handler();

Then create Runnable like this

Runnable runnable= new Runnable() {
        public void run() {
            //do your work here
        }
    };
//start like this
runnable.run();
//stop like this
handler.removeCallbacks(runnable);
Omar Hayat
  • 378
  • 2
  • 12