Search code examples
androidmultithreadingterminate

How can I terminate thread properly in Android System?


I have a question. Recently I develop simple "Logging system" for Android. There is one singleton class which name is "Logger".

protected Logger(){
....
_logHandler = new LogHandler(_logQueue);
_logHandler.start();
.... 
}
public static Logger getInstance(){
    ...
}

In "Logger", one thread is running just like below.

@Override
public void run() {
   try{
        while (isAlive){
            execute();                     
            synchronized (lock) {
                try {
                    while (isPaused) {
                        lock.wait();
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }finally {
                    shutDown();
                }
            }
        }
    }catch(InterruptedException e){
        e.printStackTrace();
    }finally {
        shutDown();
    }
}
public void requestShutDown(){
    isAlive = false;
    interrupt();
}

What i want is when application is terminated, I would like to call "requestShutDown()" method to stop thread above. But i can't find proper moment.

So, Do I have to When onPause() method executed in Activity, call requestShutDown(). And onResume() method executed in Activity, call thread.start() again?

Is there another way?

Or When Application is terminated, all the resources in application(include thread, Logger class in above) are garbage collected properly?

thanks in advance.


Solution

  • @dwnz Thank you!! Finally, I call "onDestory()" method in MainActivity. In onDestory(), if isFinishing() of Activity is true, it will be terminated(Of course, this is not "necessary and sufficient condition".)