How to stop or destroy a running Thread
you cannot destroy...only the android will stop the thread when requires.. you cannot stop or destroy it.. instead try like this..
class MyThread extends Thread
{
void run()
{
while(bool){
//My code which takes time.
}
}
}
//-------------------------- To run the thread
MyThread mThread = new MyThread();
mThread.start();
now when u want to stop the thread... change bool value to false
bool=false;
now your code doesnt run... and you can start new thread...
How do I kill an Android thread completely?
to kill the thread , i think you can do like this :
myService.getThread().interrupt();
NOTE : the method Thread.stop()
is deprecated
EDIT : : try this
public void stopThread(){
if(myService.getThread()!=null){
myService.getThread().interrupt();
myService.setThread(null);
}
}
How I can stop thread in Android
You can put a flag inside your thread:
public class Main2Activity extends AppCompatActivity {
TextView mTextField;
Button stop;
Activity myActivity;
PrimeThread T1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
myActivity=this;
mTextField = (TextView) findViewById(R.id.counter);
T1=new PrimeThread();
T1.start(); }
public void stop(View view){ T1.stopRunning(); }
class PrimeThread extends Thread {
int i=10;
boolean running = false;
public void run() {
running = true;
while(running && i < 10){
i++;
myActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mTextField.setText("00:0"+i);
}
});
i--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stopRunning(){
running = false;
}
}
}
Is this a prefect way to stop handlerthread?
You can use this as a safe way to stop threads:
if (safeThread!= null) {
safeThread.quit();
safeThread = null; // Object is no more required.
}
You can use safeThread.quitsafely
as well.
How to stop a thread?
In general, you don't forcibly stop threads because it's dangerous. You set a flag that tells the thread in question to exit from it's thread loop under controlled circumstances.
Your thread loop looks something along these lines:
void run() {
while (shouldContinue) {
doThreadWorkUnit();
}
}
And somewhere else you set the shouldContinue
variable and wait for the thread to finish:
...
thread.shouldContinue = false;
thread.join();
...
(All this is likely not correct Java, since I don't do Java. View it as pseudo code and modify for your actual language/thread library/etc.)
Where to stop/destroy threads in Android Service class?
Addendum: The Android framework provides many helpers for one-off work, background work, etc, which may be preferable over trying to roll your own thread in many instances. As mentioned in a below post, AsyncTask is a good starting point to look into. I encourage readers to look into the framework provisions first before even beginning to think about doing their own threading.
There are several problems in the code sample you posted I will address in order:
1) Thread.stop() has been deprecated for quite some time now, as it can leave dependent variables in inconsistent states in some circumstances. See this Sun answer page for more details (Edit: that link is now dead, see this page for why not to use Thread.stop()). A preferred method of stopping and starting a thread is as follows (assuming your thread will run somewhat indefinitely):
private volatile Thread runner;
public synchronized void startThread(){
if(runner == null){
runner = new Thread(this);
runner.start();
}
}
public synchronized void stopThread(){
if(runner != null){
Thread moribund = runner;
runner = null;
moribund.interrupt();
}
}
public void run(){
while(Thread.currentThread() == runner){
//do stuff which can be interrupted if necessary
}
}
This is just one example of how to stop a thread, but the takeaway is that you are responsible for exiting a thread just as you would any other method. Maintain a method of cross thread communcation (in this case a volatile variable, could also be through a mutex, etc) and within your thread logic, use that method of communication to check if you should early exit, cleanup, etc.
2) Your measurements list is accessed by multiple threads (the event thread and your user thread) at the same time without any synchronization. It looks like you don't have to roll your own synchronization, you can use a BlockingQueue.
3) You are creating a new Socket every iteration of your sending Thread. This is a rather heavyweight operation, and only really make sense if you expect measurements to be extremely infrequent (say one an hour or less). Either you want a persistent socket that is not recreated every loop of the thread, or you want a one shot runnable you can 'fire and forget' which creates a socket, sends all relevant data, and finishes. (A quick note about using a persistent Socket, socket methods which block, such as reading, cannot be interrupted by Thread.interrupt(), and so when you want to stop the thread, you must close the socket as well as calling interrupt)
4) There is little point in throwing your own exceptions from within a Thread unless you expect to catch it somewhere else. A better solution is to log the error and if it is irrecoverable, stop the thread. A thread can stop itself with code like (in the same context as above):
public void run(){
while(Thread.currentThread() == runner){
//do stuff which can be interrupted if necessary
if(/*fatal error*/){
stopThread();
return; //optional in this case since the loop will exit anyways
}
}
}
Finally, if you want to be sure a thread exits with the rest of your application, no matter what, a good technique is to call Thread.setDaemon(true) after creation and before you start the thread. This flags the thread as a daemon thread, meaning the VM will ensure that it is automatically destroyed if there are no non-daemon threads running (such as if your app quits).
Obeying best practices with regards to Threads should ensure that your app doesn't hang or slow down the phone, though they can be quite complex :)
Related Topics
Remove Line Break in Tablayout
Android Mediaplayer Throwing "Prepare Failed.: Status=0X1" on 2.1, Works on 2.2
How to Get Unique Device Hardware Id in Android
Android Deep Linking: Use the Same Link for the App and the Play Store
Default Interface Methods Are Only Supported Starting with Android 7.0 (Nougat)
Can't Accept License Agreement Android Sdk Platform 24
How to Store an Integer Array in Sharedpreferences
Override Android Backbutton Behavior Only Works on the First Page with Phonegap
How to Insert a SQLite Record with a Datetime Set to 'Now' in Android Application
How to Perform Collection Group Query Using Document Id in Cloud Firestore
Centering Recyclerview Items with Flexboxlayoutmanager
How to Use Autocompletetextview and Populate It with Data from a Web API
How to Receive Serial Data Using Android Bluetooth
Difference Between APK (.Apk) and App Bundle (.Aab)
Fragment Over Another Fragment Issue
Tabhost with Fragments and Fragmentactivity
Accessing Contents of R.String Using a Variable to Represent the Resource Name