简体   繁体   中英

Creating singleton class from a remote service android

I have created a remote service. In this remote service i am creating a singleton object. Once created this object should stay till its garbage collected. Now when i access this object from inside the singleton class i getting correct object. but when i am accessing it from outside class it singleton object is null and my class is getting created again. I am loosing all the initialised object.

my singleton class is as follows

class myFactory {

    private static myFactory instance;

    private myFactory(){
    }

    public static myFactory getInstance(){
        if(instance == null) {
            instance = new myFactory();
        }
        return instance;
    }
} 

I tried to overide finalize in singleton class to check if the object gets garbage collected but it doesnt come in that function.

Outside the connection factory object where ever i access this singleton object i am getting null and therefore new object is created > what am i doing wrong?

This is a Singleton, and I don't see why it shouldn't work. But I guess you are trying to use the Singleton in some kind of IPC-context, that would be the problem (since a remote service is afaik always a new Thread).

Question is: Why do you need a Singleton...isn't there a nicer solution? I don't know your whole Service structure, but maybe it makes sense to get the instance of the Factory while binding to the service.

It could help, if you can give more information

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