0

my thread is basically a loop of some actions.

I have set a few checks in my loop, to check basically if a boolean is still true or false. The boolean is set to true when starting the service and set to false when the service is being stopped. More specifically, I set the boolean to false in onDestroy() method of my Service class.

Example:

  public class MyThread extends Thread{
   
    
private boolean active; 
    
public void setBoolean(boolean active)
    this.active=active;
    }
    }
    
    public class MyService extends Service{
    
    private Mythread mythread;
    
    @Override
    public void onDestroy()
    {
    mythread.setBoolean(false);
    }
    }

The issue is that when a Service is being stopped by the system, onDestroy() method is not called. So, how can I properly stop the thread when the service is no longer running?

zaxunobi
  • 51
  • 9
  • I think jvm supports shutdown hooks. – Barracuda Jan 10 '22 at 14:01
  • Maybe this will help https://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java – Barracuda Jan 10 '22 at 14:03
  • Are you sure onDestroy is not called? Because if it's an android's service and it has a specific contract, it should be called. The problem you might have is not that onDestroy is not being called, but it's being called in different thread and you are not using any synchronization when accessing the boolean field. – Barracuda Jan 10 '22 at 14:05
  • @Barracuda according to the quick research I made, this is not true if you force-stop the service. – hfontanez Jan 10 '22 at 14:10
  • "Are you sure onDestroy is not called?" Yes, when killed by the system it's not called. – zaxunobi Jan 10 '22 at 15:55

1 Answers1

0

It helps to know exactly what you mean by "when the service is being stopped." I found 3 links related to your problem that I am sure will help to solve your issue (or at least to fully understand it):

TL:DR - If you are forcing stop, onDestroy() will most likely not get called.

Even if the first helps, read through the rest.

hfontanez
  • 5,774
  • 2
  • 25
  • 37
  • When the service is being stopped for whatever reason. For instance, when the service is being stopped by the user there are no issues because onDestroy() is called, therefore signaling to my thread that it should stop. However, when the service is killed by the system (force-stop), as you said onDestroy() won't be called. So how can I tell my thread to stop since the service is no longer running? – zaxunobi Jan 10 '22 at 15:58
  • @zaxunobi Did you follow something similar to [this recommendations](https://automationchronicles.com/android-service-with-multiple-threads/)? – hfontanez Jan 10 '22 at 17:06