我今天正在采访其中一位候选人。我问了一个非常常见的问题:如何为 Android 应用程序添加持续播放音乐的可能性,即使当手机方向改变时 Activity 被破坏。预期的答案是:创建负责播放音乐的服务。相反,该候选人建议在应用程序中创建一些单例。
这也是正确答案吗?我认为它应该有效 - Singleton 类将加载到内存中并永远保留在内存中;我的同事建议这个单例将随着 Activity 的销毁而被销毁,因为不再有任何引用。
最佳答案
Is this also a correct answer?
恕我直言,没有。
Singleton class will be load to memory and will stay in memory forever
没有。 Processes get terminated当它们不再处于前台时,为其他应用程序释放系统 RAM。确定何时发生这种情况取决于很多变量...其中之一是您是否有正在运行的 Service
。
my colleague suggest this singleton will be destroy with destroyed activity, because there won't be any reference any longer.
没有。 Java 中的单例是作为静态字段实现的。只要该字段具有对该对象的引用,该对象就无法被垃圾收集。默认情况下,仅销毁 Activity 不会神奇地将 static
字段设置为 null
。
关于java - Android:单例而不是服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35777158/