singleton class that survives Process termination

倾然丶 夕夏残阳落幕 提交于 2019-12-13 09:15:19

问题


I've read several post regarding singleton class destruction or singleton pattern is bad in android like this and this

But I am not able to understand how to declare a singleton class properly or use sharedpreference for persistance can anyone provide any example on how to maintain global objects across application or how to achieve this in proper way any help is appreciated.


回答1:


I think this link you mentioned is quite good.As my personal experience the best way to maintain global objects in an application is to use a class that extends from Application class, then you can manage objects by setter and getter methods in that class.This technically works like a Singleton in android except most of house keeping is done by android so it's very wise to use this mechanism instead of singleton. On the other hand shared preferences has entirely different job and used for mainly storing some user data and behavior




回答2:


To save data between process termination you have to use serialization in any form.

The easiest way is to use sharedpreferences + gson.

Singleton would not help because all data with the process will be wiped, OS have a handler to save state in "low memory" situations but it still uses serialization (bundles).

You may use singleton with sharedpreferences, data clients (activities) have to notify about destruction, so singleton can dump data. At start singleton will load data again.

But be aware of possible inconstancy - what if an app will crash?

Things get trickier with multiple processes in one application.



来源:https://stackoverflow.com/questions/39115735/singleton-class-that-survives-process-termination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!