android释放内存的一个办法
2023-01-08 16:18:40
michael007js
106
public static interface OnLowMemoryListener {
void onLowMemoryReceived();
}/* 何问起 hovertree.com */
step 2:android application文件中添加如下代码
//初始化
private ArrayList<WeakReference<OnLowMemoryListener>> mLowMemoryListeners;
/* 何问起 hovertree.com */
public MyApp() {
mLowMemoryListeners = new ArrayList<WeakReference<OnLowMemoryListener>>();
}/* 何问起 hovertree.com */
//注册监听
public void registerOnLowMemoryListener(OnLowMemoryListener listener) {
if (listener != null) {
mLowMemoryListeners
.add(new WeakReference<MyApp.OnLowMemoryListener>(listener));
}
}
//移除监听
public void unregisterOnLowMemoryListener(OnLowMemoryListener listener) {
if (listener != null) {
int i = 0;
while (i < mLowMemoryListeners.size()) {
final OnLowMemoryListener l = mLowMemoryListeners.get(i).get();
if (l == null || l == listener) {
mLowMemoryListeners.remove(i);
} else {
i++;
}
}
}
}/* 何问起 hovertree.com */
//内存空间过低的时候,被系统调用
@Override
public void onLowMemory() {
super.onLowMemory();
int i = 0;
while (i < mLowMemoryListeners.size()) {
final OnLowMemoryListener l = mLowMemoryListeners.get(i).get();
if (l == null) {
mLowMemoryListeners.remove(i);
} else {
l.onLowMemoryReceived();
i++;
}
}
}/* 何问起 hovertree.com */