[英]a Java singleton class does not call its constructor on Android
I'm working on a game with libGdx which runs on Android. 我正在使用在Android上运行的libGdx进行游戏。 I have some situation related with singleton pattern.
我有一些与单例模式有关的情况。
in my app, all drawing calls are managed by a class called "Spritepool". 在我的应用中,所有绘图调用均由一个名为“ Spritepool”的类进行管理。 it runs on main thread, doing texture updates, sorting, drawing... so I made it a singleton.
它在主线程上运行,进行纹理更新,排序,绘制...因此我将其设置为单例。
and it works almost fine.. but app crashes when restart after quit once. 并且它几乎可以正常工作..但是退出一次后重启时,应用崩溃。
I figured it's because singleton class Spritepool does not call its constructor when app starts once again... 我认为这是因为当应用再次启动时,单例类Spritepool不调用其构造函数...
Changing Spritepool into an enum singleton was not a solution. 将Spritepool更改为枚举单例不是解决方案。 my Spritepool class looks like this..
我的Spritepool类看起来像这样。
public enum Spritepool {
INSTANCE;
BitmapFont debug = new BitmapFont();
public static Spritepool get(){ return INSTANCE; }
Spritepool(){
Gdx.app.log("sprite pool", "=== sprite pool constructor calling... ");
}
...
...
public void workingCodes(){...}
}
I have now removed all of initializations from constructor Spritepool() except a log. 现在,我从构造函数Spritepool()中删除了除日志外的所有初始化。 When first launch of app, log of constructor prints well and member "debug" instanciates good.
首次启动应用程序时,构造函数的日志打印良好,成员“ debug”表示良好。 After quit app and relaunch, all of app cycle works normally and Spritepool() log gone, and member "debug" pointing a garbage.. (not new BitmapFont()..)
退出应用程序并重新启动后,所有应用程序周期均正常工作,Spritepool()日志消失,成员“ debug”指向垃圾。(不是新的BitmapFont()。)
Is this a normal behavior of common singleton class on android? 这是Android上常见的单例类的正常行为吗? (I think not.. maybe I'm doing wrong somewhere) .. and what should I do to make it right?
(我认为不是..也许我在某处做错了..)我应该怎么做才能使它正确? any advice will be appreciated.
任何建议将被认真考虑。 thanks.
谢谢。
Why do you use an enum? 为什么使用枚举?
Try this: 尝试这个:
public class Spritepool { private Spritepool INSTANCE; 公共类Spritepool {private Spritepool INSTANCE;
BitmapFont debug = new BitmapFont();
public static Spritepool get(){
if (INSTANCE == null) INSTANCE = new Spritepool();
return INSTANCE;
}
Spritepool(){
Gdx.app.log("sprite pool", "=== sprite pool constructor calling... ");
}
...
...
public void workingCodes(){...}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.