Arhimed Arhimed - 1 month ago 13
Android Question

What's the most "death-resistant" component on Android?

I'm looking for the most suitable class to be a dispatcher for AsyncTasks invoked from my Activities.

I think it could be one of these:

  1. subclass of Application;

  2. subclass of Service;

  3. my own static stuff.

As for me - it's simlier to implement the 3rd choice. But the question is will it be more "death-resistant" than Service or Application? Also it's very interesting what will live longer - Application or Service? My guess is the Application lives as long as the app (task in terms of Android) process lives.

So basically I need to range those options by their "death-resistant" quality, because I'd like to rely on the most "static" thing.


Originally the question was asked in 2010, when (1) Android was new platform for developers and (2) Google documentation was too vague (in some cases it was even misleading) about app components life-cycles and the entire app process life-cycle.

Answer Source

You should definitely use a Service.

The main reason behind this - Service has it's own documented life-cycle, while Application doesn't. Application instance, like any of your static variables, can be killed by system almost at any time, you will not receive any callback and can't stop this process. So, any unsaved data (all static variables) will be lost.

On the other hand, Service can't be killed by system silently, at least onDestroy() method should be called first. Having such callback, you can save your state to some persistent memory (like SharedPreferences, file, database, etc) and restore that state next time your Application or Service starts.