简体   繁体   中英

a Java singleton class does not call its constructor on Android

I'm working on a game with libGdx which runs on Android. I have some situation related with singleton pattern.

in my app, all drawing calls are managed by a class called "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...

Changing Spritepool into an enum singleton was not a solution. my Spritepool class looks like this..

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. When first launch of app, log of constructor prints well and member "debug" instanciates good. After quit app and relaunch, all of app cycle works normally and Spritepool() log gone, and member "debug" pointing a garbage.. (not new BitmapFont()..)

Is this a normal behavior of common singleton class on 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;

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(){...}

}

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.

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