你的位置:首页 > 操作系统

[操作系统]android释放内存的一个办法


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