I have a thread inside a service and I would like to be able to stop the thread when I press the buttonStop
on my main activity class.
In my main activi
You can't stop a thread that has a running unstoppable loop like this
while(true)
{
}
To stop that thread, declare a boolean
variable and use it in while-loop condition.
public class MyService extends Service {
...
private Thread mythread;
private boolean running;
@Override
public void onDestroy()
{
running = false;
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startid) {
running = true;
mythread = new Thread() {
@Override
public void run() {
while(running) {
MY CODE TO RUN;
}
}
};
};
mythread.start();
}
You call onDestroy() method for stop service.