简体   繁体   中英

how do I override onTrimMemory in android

The Application class in android provides the methods onTrimMemory and onLowMemory. I don't really understand them (of course other than the obvious linguistic meaning). How might I implement the method onTrimMemory? What does it mean to trim memory? I am obviously looking for detail technical answers. Beyond emptying caches (should I do that?), there seems to be something more specific meant by trimming. How is that done in android? Is it an OS thing? Is it a system level thing? Should I worry about it? I would really love to know how to override it.

What does it mean to trim memory?

Let go of objects, so they can be garbage-collected.

Beyond emptying caches (should I do that?)

Yes.

there seems to be something more specific meant by trimming

Not really. Android is saying "hey, um, things are getting a big snug on system RAM, could you cut back" for lighter levels, and is saying "gee, this is a real nice process you got here — it would be a shame if we had to terminate it" for more severe cases.

Bear in mind that with Dalvik (and I assume ART), garbage collection can actually reduce your process' working set size (aka, amount of system RAM you are using), and so by reducing your heap usage, you make it a bit less likely that Android will terminate your process while you are in the background.

How is that done in android?

Let go of objects, so they can be garbage-collected. Mostly, this should refer to caches. Anything else, you should be letting go of as your app runs, based on business rules. So, for example, while you could terminate background threads in onTrimMemory() (and therefore let go of any objects only reachable via those threads), there are probably better/earlier points in time to terminate those threads, if they are not adding any value.

Is it an OS thing?

I do not know what you consider an "OS thing" to be.

Is it a system level thing?

I do not know what you consider an "system level thing" to be.

Should I worry about it?

If you are manually maintaining a cache that might consume a lot of memory, ideally yes.

If you are using a third-party library that has a cache (such as an image-loading library), see whether they register for onTrimMemory() themselves. If not, you might see if the library has some API for you to tell it to reduce the cache, then call that yourself from onTrimMemory() .

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