In my Android application I have a Singleton class. It works like a charm when the application task is alive. But after the application task is being killed, the Singleton class gets destroyed, which is obviously. I need to keep this class always alive. Is it possible? And what is the best approach to have this class never been killed by Android system, do I need to use a background Service in this situation?
Using a Service for the purpose of trying to ensure a Singleton class always stays in memory for subsequent invocations of the application would be terribly bad design. It's simply not what Services are for. See: http://www.androidguys.com/2009/09/09/diamonds-are-forever-services-are-not/ .
If you want to ensure that a bunch of data is kept around ready for the next time the application is created then you should choose an appropriate means to persist that data. This could be, for example, by using SharedPreferences or SQL , or a cache, etc. depending on what kind of data you're trying to keep around. Then, design all Activity classes to properly cope with the scenario where they're resumed when all Singleton data is not in an initialised state.
I personally maintain a complex scientific application that relies on having quite a lot of singleton data held in RAM. One significant problem I encountered during early stages of development is that it's possible for the following situation to happen:
Service
s it uses while the user interacts with other apps. To cope with the above scenario, the key thing I did was to ensure all Activities don't just assume that global (Singleton) data is present and intact when the Activity is started. Each Activity in my application that depends on the global Singleton data checks that data first and, if it is not initialised, calls a method in my Application class to trigger regeneration of that data (which in my case involves retrieving that data from a file from the SD card).
So in short, handling global / Singleton data in Android takes some care and thought. You cannot force the system to indefinitely avoid killing your Application and therefore all of your Singleton data. The key things I learned therefore are to persist and retrieve your data, and design your Activity classes to properly handle the situation where no Singleton data is found to be already initialised when that Activity is created.
是的,您需要使用后台服务。后台服务是与其他所有组件相比在被杀死方面具有最高优先级的组件,但是请确保或服务应连续运行。
Try using moveTaskToBack() . That should do the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.