首页 > 解决方案 > Android:线程创建另一个单例实例

问题描述

我的应用程序中有一个singleton对象。

public class Single {

    private Context mContext;
    private static Single sInstance;

    public synchronized static Single getInstance(Context context) {
        if(sInstance == null) {
            sInstance = new Single(context);
        }
        return sInstance;
    }

    private Single(Context context) {
        mContext = context;
    }
}

getInstance当我运行我的应用程序时,我通过在主线程上调用方法来创建此类的实例。但是当我在同一进程中从单独的线程调用getInstance方法时,它会创建另一个类实例Single

我的代码不应该Single每个进程只有一个类对象吗?如何将其更改为每个进程具有单个实例。

我正在做的是:

private class ProfileBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.v(TAG, "onReceive :: " + action);
        Handler handler = mHandlerMap.get(action);
        if (handler != null) {
            handler.onReceive(context, intent, device);
        }
    }
}

interface Handler {
    void onReceive(Context context, Intent intent, BluetoothDevice device);
}

private void registerIntentReceiver(BroadcastReceiver receiver, IntentFilter filter) {       
    mContext.registerReceiver(receiver, filter, null, mReceiverHandler);      
}

我正在注册我ProfileBroadcastReceiver的 inregisterIntentReceiver方法。我还传递了一个android.os.Handler对象,以便该onReceive方法在单独的线程上运行。这是我调用getInstance()方法的地方:

private class StateChangedHandler implements EventManager.Handler {

    public void onReceive(Context context, Intent intent, BluetoothDevice device) {
        ..
        Single single = Single.getInstance(context);
        .
        .
    }

}

标签: javaandroidsingletonandroid-10.0

解决方案


为了避免内存泄漏,您必须从类中删除该context字段。Single这段代码在我的项目中运行良好。


推荐阅读