java - 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);
.
.
}
}
解决方案
为了避免内存泄漏,您必须从类中删除该context
字段。Single
这段代码在我的项目中运行良好。
推荐阅读
- django - 是什么导致我的 Windows 10 防火墙阻止 Docker 驱动器共享?
- java - 在标准 PMD 圈复杂度插件上获取 ClassNotFoundException
- firebase - 没有创建 Firebase 应用“[DEFAULT]”尝试构建私人消息传递系统时出错
- swift - 无法在视图控制器之间传递数据
- ios - 关闭应用程序最近选项卡后 PopToRootViewController 不工作
- reactjs - 模块未定义用于从外部包动态导入命名导出
- javascript - 为什么手动重新连接Socket.IO时不会触发重新连接功能
- javascript - 如何用Javascript中的唯一值替换文本中的不同单词?
- django - 如何使用 Django Rest Framework 从所有页面获取 Json 记录?
- elasticsearch - 手动进行弹性搜索快照,升级后是否可用