简体   繁体   中英

Allocating HEAP memory on demand

I have an android app in which i make a call to obtain lots of data, i was receiving the OutOfMemoryException error so I investigated and found the solution:

Add android:largeHeap = true , this works great, I no longer get errors BUT i also read this is not good because it may block the users other apps. Is there a way to assign a fix number of HEAP the app can use?. While debugging with logcat I saw that it wont be much what I would need extra from the base or default HEAP space that it is provided, but it's large enough to cause the OutOfMemoryException .

New to android and trying to figure this out, i wouldn't like my app users to get their phone messed up because I took the whole HEAP memory.

PS: The app is good for phones with Android version 4.0 and up.

Unfortunately, there is no way to assign a fix number of HEAP space to your app, and the assigned heap space can be vary based on the devices.

One alternative is check available space dynamically at run time, and do some job based on the analysis. There are several ways to check available memory space in Android, but I prefer using getMemoryClass like this. (I copied the code from Square's Picasso library )

//memory class is MB units.
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;

int memoryClass = am.getMemoryClass();
if (largeHeap && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM