简体   繁体   English

我的单身人士会被杀死吗?

[英]Will my singleton be killed?

I have an application where I create a foreground service to make sure a user initiated upload continues even if the user quits the app or app is killed by memory pressure. 我有一个应用程序,在该应用程序中我创建了前台服务,以确保即使用户退出应用程序或由于内存不足而终止应用程序,用户启动的上传操作仍继续进行。

Both the service and app use a singleton to pass data around. 服务和应用程序都使用单例来传递数据。 I know this is not the best solution, so kindly ask to refrain from comments about bad-bad singletons as the question is not in this but in the following: 我知道这不是最好的解决方案,因此请不要发表有关坏单身人士的评论,因为问题不在此,而在以下内容中:

When I close the app, my foreground service continues running and can access the singleton. 当我关闭应用程序时,我的前台服务将继续运行并可以访问单例。 Is there a risk of the singleton being garbage collected due to memory pressure or are there any other memory related risks of using a singleton in this case? 是否存在由于内存压力而导致垃圾回收垃圾的风险,或者在这种情况下是否还有其他与内存相关的风险?

  1. There is nothing bad about singletons. 单身人士没有什么不好的。 But as any other pattern or method it just could be used improperly. 但是,与其他任何模式或方法一样,它可能会被错误地使用。
  2. Due to memory pressure or any other reason a system could kill your app. 由于内存压力或任何其他原因,系统可能会杀死您的应用程序。 But your Service will be relaunched later. 但是您的Service将在稍后重新启动。
  1. Singleton pattern is a very useful pattern in the system due to that it is a static format. 单例模式是系统中非常有用的模式,因为它是静态格式。 Exactly one object is needed to coordinate actions across the system. 恰好需要一个对象来协调整个系统的动作。 You dont need to worry about the duplication or you accidentally create multiple modules. 您无需担心重复,也可以不小心创建多个模块。
  2. A foreground service is a service that's considered to be something the user is actively aware of(has focus) and thus not a candidate for the system to kill when low on memory. 前台服务是一种被认为是用户主动意识到的(具有焦点)的服务,因此不适合当内存不足时被系统杀死的服务。 The skeleton object will not be killed. 骨架对象不会被杀死。

Static variables are only destroyed when the application is killed. 静态变量仅在终止应用程序时销毁。 So they won't just randomly disappear while your service is running. 因此,它们不仅会在您的服务运行时随机消失。 However if your entire service restarts you do have to account for the possibility of not having the singleton when it restarts. 但是,如果整个服务重新启动,则必须考虑重新启动时没有单例的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM