0

It seems that Looper (at least the one that is created with HandlerThread) never gets garbage collected even if not referenced by other code. I am aware of quit() and quitSafely() methods, however in my application I am not sure who would be responsible for calling one of these methods.

What is the right way to shut down the Looper in an application with multiple activities and where Handlers created on this Looper have lifecycle different from ones of the activities. It can't be onDestroy() of any of the activities. If I don't shut it down and the process is not killed by OS - new Looper may be created on next app "launch" and this one will leak. Alternatively, create once, store in a static field, never quit, let it leak once. The last one seems to be the safest and easiest to implement so far.

justme
  • 31
  • 2

1 Answers1

0

What is the right way to shut down the Looper in an application with multiple activities and where Handlers created on this Looper have lifecycle different from ones of the activities

Use a Service.

It has own Looper, own lifecycle, can work in main thread like activity.

You can use LocalBroadcastManager to get callback from it.

Lionel Briand
  • 1,732
  • 2
  • 13
  • 21
  • Are you suggesting to use `Service` for managing `Looper`'s lifetime? If so, as I said before - I don't even know when to shut it down. In this case `Service` should be roughly equivalent to my static field. Alternatively, if you are suggesting to use `Service` to do work on the non-main thread, I am particularly interested in `Handler`s sending `Message`s to each other. – justme Jul 01 '16 at 22:54
  • With a service you not have to deal with `Looper`'s lifetime. You can just bind it to `Service` lifetime and let the System to manage it. If you really want to use `Handler` you can use a [ResultReceiver](http://stackoverflow.com/questions/4510974/using-resultreceiver-in-android) to handle `Message`s from Service. – Lionel Briand Jul 02 '16 at 09:00