0

please hold back on the downvotes for a second and read.

After my question Is there a way to create a controlling instance that controls several activities of my app?

and after reading detect when application is closed

i am wondering... i have lots of activities in my app, and several services, i access about all the hardware that the device has. Access to those things makes sense for as long as the app is running. Activities can change but the need for access to those things is there in every single one of them (slight exaggeration).

I know of two ways that seem suitable for my needs.

1) i extend Application and instantiate some objects there that access or calculate stuff that is needed everywhere

2) i do the same in a subclass of Activity

In both cases i would like to unregister broadcastreceivers and stop services. Services are not bound (for a reason). So whats the proper way to close and unregister things in all those cases that can happen ?

  • its possible that onDestroy is not called

  • i am not notified of my process being closed/killed by the system

So how do i create something that is always there for all my activities but stops and cleans up whenever my app is being closed ?!

Community
  • 1
  • 1
NikkyD
  • 2,209
  • 1
  • 16
  • 31

1 Answers1

1

You can't, never ever never create something that is 'always there' in Android, it is simply not part of the architecture. Even with a startforeground service if the device is low on memory or asleep your services can still be destroyed (and calling ondestroy is not guaranteed as you point out).

The most reliable way I've found to keep something 'alive forever' in a quasi-sense is to set a repeating alarm schedule with RTC_WAKEUP and use a WAKE LOCK.

The problem with those things however is that they will eat through battery like no tomorrow! If you are just concerned about all that stuff while the screen is on, an inexact repeating RTC alarm w/o wake lock seems to work well for most scenarios.

Edit: I sorta answered your question indirectly, but in addition to the above, when you are done with a resource declare it null or unregister it. If you have long living services with stuff registered and Android decides to kill your service and not call onDestroy, well there is not much you can do about that, just move on (and be sure you are save your states in persistent storage so you can retreive them at next init at the state they were last left off at.)

logray
  • 2,332
  • 1
  • 29
  • 30