android释放内存的一个办法

时间:2023-03-08 16:41:55

step 1:定义一个监听接口

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 */

step 3:那些浪费内存的地方,比如图片缓存,可以实现并注册这个监听

推荐:http://www.cnblogs.com/roucheng/p/androidtuichu.html