I have been working on app that has several activities and services.
In one on my activity, I have starting a thread, which is doing some important work for me in background.
Following is code for thread
OnCreate()
{
Runnable runnable = new MyRunnableThread();
MyThread= new Thread(runnable);
MyThread.start();
}
private class MyRunnableThread implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// Doing some work here ..
Thread.sleep(2000); // Pause of 2 Second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
FirebaseCrash.report(e);
}
}
}
}
Now this is how my thread is running..
Now i am stopping this thread using following code
MyThread.Intrrupt();
This will stop my thread to execute ..
In my scenario, sometime when app crashes, these thread keep on running and thus causing misbehave in my app logic..
I want these thread to be stopped immediately in case of app crashes.
Is it the correct way of stopping the thread execution and stop ?
I am using thread in service class also and in state of confusion that there might be multiple threads of same instance running in app at a time because previous was not stopped correctly !!!
Please guide !!!