Java Android:线程创建另一个Singleton实例
我的应用程序中有一个Java Android:线程创建另一个Singleton实例,java,android,singleton,android-10.0,Java,Android,Singleton,Android 10.0,我的应用程序中有一个singleton对象 public class Single { private Context mContext; private static Single sInstance; public synchronized static Single getInstance(Context context) { if(sInstance == null) { sInstance = new Single(c
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
类的实例
我的代码不应该每个进程只有一个单个类的对象吗?如何将其更改为每个进程只有一个实例
我正在做的是:
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);
}
我正在registerIntentReceiver
方法中注册我的ProfileBroadcastReceiver
。我还传递了一个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);
.
.
}
}
为了避免内存泄漏,必须从单个
类中删除上下文
字段。这段代码在我的项目中运行良好。如何验证它没有返回相同的实例?我在其构造函数中添加了日志并进行了检查。我还使用toString()方法进行了检查。我得到了一个新的实例。你是否尝试使sInstance
?请确认这个问题只发生在Android 10上?你能展示一下你的代码来创建这个单例实例吗,一个在主线程中,另一个在后台线程中。是的,它只发生在Android 10中。我添加了更多的代码。您能解释一下吗。上下文
对象即使在导致内存泄漏的活动被破坏后仍然是活动的,您不应该在静态类中维护活动
、上下文
和视图
字段。如果想在静态类中使用上下文,必须使用WeakReference
。