静态实例是android服务中的null

问题描述 投票:0回答:3

有时从服务调用主类的实例时,其实例变为空。

我首先通过调用“ MainClass.init()来统计单例。从单例MainClass调用“ startOnboarding()”后,服务启动。

“ onStartCommand()”方法将调用单例-MainClass.getInstance(),有时该值为null。

// Singleton
public class MainClass {
    private static MainClass instance = null;

    public static void init() {
        instance = new MainClass();
    }

    public static MainClass getInstance() {
        return instance;
    }

    private MainClass() {
    }

    public void startOnboarding(Context context) {
        Intent intent = new Intent(context, OnboardingService.class);
        context.startService(intent);
    }
}

public class OnboardingService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (MainClass.getInstance() == null) {
            // This happened sometimes
            logger.error("NO MAIN INSTANCE");
            return;
        }
        ....
    }

    public class OnboardingServiceBinder extends Binder {
        OnboardingService getService() {
             // Return this instance of LocalService so clients can call public methods
            return OnboardingService.this;
        }
    }

    // Binder given to clients
    private final IBinder mBinder = new OnboardingServiceBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}

在Samsung Galaxy 10上测试。

您能帮忙吗?

android service static singleton
3个回答
0
投票
public static MainClass getInstance() { if (instance == null) { instance = new MainClass(); return instance; } return instance; }

这样,实例将在您需要时永远不会为空。


0
投票
public final class Singleton { private static volatile Singleton _instance = null; private Singleton() {} public static synchronized Singleton getInstance() { if (_instance == null) synchronized (Singleton.class) { if (_instance == null) _instance = new Singleton(); } return _instance; }

}

© www.soinside.com 2019 - 2024. All rights reserved.