Several code processing methods for Android Memory Optimization
The following describes several code processes for Androi memory optimization. The sample code is for reference only:
? 1. Generate Bitmap:
InputStream is = this. getResources (). openRawResource (R. drawable. pic1 );
BitmapFactory. Options options = newBitmapFactory. Options ();
Options. inJustDecodeBounds = false;
Options. inSampleSize = 10; // width, hight is set to the original 10-minute-one
Bitmap btp = BitmapFactory. decodeStream (is, null, options );
2. Reclaim Bitmap:
If (! Bmp. isRecycle ()){
Bmp. recycle () // reclaim the memory occupied by the image
System. gc () // remind the system to recycle it in time
}
? When recycle () is called, a thread is enabled for processing. Only the system knows when to recycle it. (Recommended JVM for garbage collection)
? This is why we call it in some places, and oom is still reported in that place.
? However, there is always a better result, which can effectively reduce the probability of oom.
Reclaim Resources
(1) // used to store the image Cache
HashMap BitmapCache = new HashMap ();
// If no image exists or already exists
If (bitmapCache. isEmpty () |! AppConst. bitmapCache. containsKey (position )){
BitmapCache. put (position, bm );
}
(2) define the FreeBitmap function. At the end of the activity, call the FreeBitmap function to recycle Resources in the map.
Private void FreeBitmap (HashMap Cache ){
If (cache. isEmpty ()){
Return;
}
For (Bitmap bitmap: cache. values ()){
If (bitmap! = Null &&! Bitmap. isRecycled ()){
Bitmap. recycle ();
}
}
Cache. clear ();
}
3. manual intervention in heap memory:
(1) improve the processing efficiency of program heap memory:
Manual Interference with GC can be considered when developing large game or resource-consuming applications. For example, VMRuntime. getRuntime (). setTargetHeapUtilization (0.75f) is called during onCreate );
(2) forcibly set the minimum memory size of the APP:
VMRuntime. getRuntime (). setMinimumHeapSize (6*1024*1024); // set the minimum heap memory size to 6 MB.