1

Suppose I have a HandlerThread in Application class which I use to do some background work. Do I need to stop this thread myself or will it be killed by OS along with Application instance? My code looks something like this.

public class MyApplication extends Application {

    private Handler handler;

    @Override
    public void onCreate() {
        super.onCreate();

        HandlerThread handlerThread = new HandlerThread("WorkerThread");
        handlerThread.start();
        this.handler = new Handler(handlerThread.getLooper());
    }

    public void runInBackground(Runnable runnable) {
        this.handler.post(runnable);
    }

}
Egis
  • 5,081
  • 5
  • 39
  • 61
  • The documentation does not state anything about a need to handle life cycle of application, so I would believe it is fairly safe to assume that it is terminated as part of the app. – cYrixmorten Nov 29 '15 at 22:25

1 Answers1

0

In general you shouldn't need to worry about terminating threads when the application is terminated. The application is not always terminated immediately, however, when the user leaves the app. In some cases it might make sense to stop the background threads, for example to optimize the battery life, when they continue to perform tasks that are no longer needed.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kaamel
  • 1,852
  • 1
  • 19
  • 25
  • If a process is terminated, so are all of its threads. But yes, the process will not necessarily be terminated, and threads left unecessarily doing active work or busy waiting will waste resources. Android framework managed threads would normally be safely blocked waiting on binder if you haven't given them something to do. – Chris Stratton Nov 29 '15 at 23:16