我已经询问过Android 上的内存泄漏,但我还不太了解内存泄漏。现在我必须保存一些接收到的数据PhoneStateListener
。单例模式很方便,因为我应该保证只有一个实例存在。
public class PhoneStateInfo {
/** -1 until the first reception */
private int mCid = -1;
/** -1 until the first reception */
private int mLac = -1;
/** 0 until the first reception */
private int mMcc;
/** 0 until the first reception */
private int mMnc;
// And so on...
private static PhoneStateInfo INSTANCE = new PhoneStateInfo();
public static PhoneStateInfo getInstance() {
return INSTANCE;
}
private PhoneStateInfo() {}
/**
* Reverts the single instance to its initial state
* But if I have 10 or 20 fields which have various default values, it will be easy to forget something
*/
void clear() {
mCid = -1;
mLac = -1;
mMcc = 0;
mMnc = 0;
mRssi = -1;
mSimState = TelephonyManager.SIM_STATE_UNKNOWN;
mDeviceId = null;
mSubscriberId = null;
mPhoneNumber = null;
}
/**
* Reverts the single instance to its initial state
* Short and clear
*/
static void clearInstance() {
INSTANCE = null; // If I delete this line, memory leaks will occur
// because the old reference is left alive will not be garbage-collected
INSTANCE = new PhoneStateInfo();
}
}
请参阅clear()
和clearInstance()
方法。我的评论在那里正确吗?