在很多APP经常会因为数据量大,或者一个页面占有内存较高,在切换到另外一个页面的时候,内存不能够暂时释放,导致切换到另外一个页面加载较慢...
Android在4.0版本后推出了onLowMemory()和onTrimMemory(...)两个回调方法,提供给开发者,提示Android APP在低内存的状态.
OnTrimMemory的主要作用就是指导应用程序在不同的情况下进行自身的内存释放,以避免被系统直接杀掉,提高应用程序的用户体验
onLowMemory()方法在使用过程只要低内存状态下,就会回调.
系统回调是在ActivityThread类中进行的:
final void handleLowMemory() { ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null); final int N = callbacks.size(); for (int i=0; i<N; i++) { callbacks.get(i).onLowMemory(); } // Ask SQLite to free up as much memory as it can, mostly from its page caches. if (Process.myUid() != Process.SYSTEM_UID) { int sqliteReleased = SQLiteDatabase.releaseMemory(); EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased); } // Ask graphics to free up as much as possible (font/image caches) Canvas.freeCaches(); // Ask text layout engine to free also as much as possible Canvas.freeTextLayoutCaches(); BinderInternal.forceGc("mem"); } final void handleTrimMemory(int level) { if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level); final WindowManagerGlobal windowManager = WindowManagerGlobal.getInstance(); windowManager.startTrimMemory(level); ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null); final int N = callbacks.size(); for (int i = 0; i < N; i++) { callbacks.get(i).onTrimMemory(level); } windowManager.endTrimMemory(); }
这里面要注意onLowMemory()方法中会调用BinderInternal.forceGc("mem");会触发系统垃圾回收,但是onTrimMemory不会,它自会提示开发者当前的内存水平.
public static void forceGc(String reason) { EventLog.writeEvent(2741, reason); Runtime.getRuntime().gc(); }
onTrimMemory(level)中level水平说明可以参考ComponentCallbacks2.java类,也可以大致看一下下面的:
这两个回调在下面中都得到实现:
四大组件除了广播,加一个Fragment.
具体程序中实现下面两个回调:
@Override public void onLowMemory() { super.onLowMemory(); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); if(level> ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN){ }else if(level>ComponentCallbacks2.TRIM_MEMORY_BACKGROUND){ }else if(level>ComponentCallbacks2.TRIM_MEMORY_COMPLETE){ }else if(level>ComponentCallbacks2.TRIM_MEMORY_MODERATE){ }else if(level>ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW){ }else if(level>ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL){ }else if(level>ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE){ } }
在不同的级别阶段处理不同的内存管理.