简体   繁体   中英

Android Stop Runnable created in new Thread

In my Android app I start a Runnable (called remoteUDPRunnable ) that establishes an UDP Connection with another device in a new Thread like this:

new Thread(remoteUDPRunnable).start();

I some cases, I want to stop that Thread (and cancel the UDP connection ) but I don't know how

I'have tried to keep the Thread instance in a variable and call myThread.interrupt() but it doesn't work.

I have also tried using a Handler like this:

final Handler remoteUDPRunnableHandler = new Handler();
remoteUDPRunnableHandler.post(remoteUDPRunnable);

So I can cancel it doing this:

remoteUDPRunnableHandler.removeCallbacks(remoteUDPRunnable);

That works but when I call the post(remoteUDPRunnable) method I get a NetworkOnMainThreadException . I have also tried to put the code inside the Runnable inside an AsyncTask but it doesn't work either.

Any ideas? I'm quite new on this and I'm a bit confused about it. Thanks

If you wrote the the class of remoteUDPRunnable yourself, you need to make sure (programmatically) the thread comes to an end.

The call thread.interrupt() only sets a flag in that thread. But if you never check it and do something with it, it's completely useless.

In your runnable you need to call Thread.interrupted() , if it returns true, initiate the shutdown of the thread. Be careful, the call Thread.interrupted() resets the interrupt flag of the executing thread.

Also, if a InterruptedException is thrown, the interrupt flag is also reset, so you might need to call Thread.interrupt() again in your runnable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM