For MIDP applications, because of the limited resources on mobile devices, weak CPU computing power, limited memory (from dozens of KB to hundreds of KB, although a handful of high-end handsets have more than 1M of dynamic memory), a small screen size, In order for a MIDP application to run on a variety of different handsets without modification, the program must have the ability to automatically adjust the Run-time parameters according to the system configuration. For example, for a cell phone with very small memory, if you download a larger image from the network, you need to allocate a large buffer, you can cause outofmemoryerror errors, so that the application to terminate directly, which will make users feel overwhelmed, or lose the user's important data.
Therefore, before attempting to allocate a large chunk of memory, first use System.GC () to try to get the garbage collector to release the memory occupied by the unwanted object, and then use the Runtime.getruntime (). Freememory () method to obtain the available memory space. If the free space is too small, give the user an alert prompt with "Insufficient memory to complete the operation" to avoid outofmemoryerror errors as much as possible.
// 示例代码:
System.gc();
int max_size = 102400; // 100KB
int free_size = (int)Runtime.getRuntime().freeMemory();
if(max_size>free_size*2/3) {
// TODO: Alert!
}
else {
byte[] buffer = new byte[max_size];
// TODO: Download image...
}