I want to close a background thread in my service in the onDestroy
method, because if I stop my service the background thread is still running. Because thread.stop()
is deprecated, I don't really know how to do it.
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
runAsForeground();
Runnable service = new Runnable() {
@Override
public void run() {
connect(client,options);
}
};
backgroundThread = new Thread(service);
backgroundThread.start();
Log.i(TAG, "onStartCommand methode called");
return Service.START_NOT_STICKY;
}
Thread life cycle is not the same as Android Context Component life cycle. Stopping the service is not enough to stop the thread which service created. Thread.interrupt()
is a option. - You should catch InterruptedException
though. If it is not enough, you can check if service is not stopped inside your connect()
method.