how do I override onTrimMemory in android - 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 (a.k.a., 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().

Related

Android Memory Management issues

I'm working on my first android application which is a big application though.. I have completed half of my app but what makes me worry is that the memory used by app.. Initially I faced the issues regarding out of memory exceptions.. I first started analyzing my app with MAT(Memory Analyzer Tool) of Android Studio, which was very difficult to track the memory usage.. My app would reach allocated space of 96mb and crash.. Then After Reading on internet i used Leak Canary which pointed out the static resources that was eating memory.. and now my app regularly gets Garbage collected but still i find the allocated space remains to be around 70 mb, Like my app starts with allocation of 30mb when i use app for about 2 min and come back to initial screen the allocated space is not same as initial... For beginners like me it is hard to track the memory usage to the core using MAT and is there a best approach or tool which would give me a clear picture of allocated space by objects.. Objects that are taking maximum space.. objects that are supposed get destroyed but not destroyed?? and retaining Image memory etc etc Thanks in advance
One of the main 'memory leakers' is the Bitmap. Sometimes when you load an image in a a View, it uses a lot of memory in the action. I used to recommend using libraries like Glide or Fresco which are better handling memory issues and have a lot of common features already implemented.
Also you could try to free resources for each activity in your onDestroy method.
Nevertheless, I would be great if you could give us a deeper overview of your project.
Regards.
There have been a few posts here related to memory management.
We have all been newbies at some point and thankfully experience and problems like these have proven to be excellent 'teachers'.
Like I have said in another post :
This will of course cause memory problems such as leaks, OOM and
unnecessary resource binding. There is absolutely no automatic way to
free up memory. You can not, under any circumstances, rely solely on
the Garbage Collector
Basically, you must ensure that you allocate only the required resources and deallocate them as soon as you know you wont need them anymore within the Lifecyce
I have wrote a more detailed explanation with code (that you can implement on your project) to deal with your memory issues which can be found here :
It can be found here
Regards,

Executing 120k queries in android

I am doing some sort of benchmark for sqlite android. If I were to pre-load total of 120k before executing, will most device have enough memory? While the queries are executing, there are also other threads that are going on so memory might be the problem. How can I make use of the onLowMemory() method? There doesn't seem to be much examples on using that method. Thanks for any advice.
Making use of the method is as easy as overriding it in your Activity.
However, read the documentation carefully:
This is called when the overall system is running low on memory, and
would like actively running process to try to tighten their belt.
While the exact point at which this will be called is not defined,
generally it will happen around the time all background process have
been killed, that is before reaching the point of killing
processes hosting service and foreground UI that we would like to
avoid killing.
Applications that want to be nice can implement this method to
release any caches or other unnecessary resources they may be holding
on to. The system will perform a gc for you after returning from
this method.
I'm not sure (and the docs don't define) if "background process" includes AsyncTask instances and services, or just backgrounded applications, but I would guess so.
So, when this method is called (if it is ever called) the System has already killed everything it could (with lower priorities than your Activity) and now asks you to release any unnecessary resources in memory.
So, If you want to react on low memory, this might be too late already.
As for the general question if most Android devices would run out of memory, I don't know. The problem is, that devices vary a lot.
I also find it hard to imagine any real live situation, in which you would need to pre-load (or stack) 120k queries before executing. You could easily stack 200 and commit those, than stack another 200 and so on.
I'm not sure why you need to benchmark this, but please don't execute 120k queries for default entries in your applications database.
You can deliver your application with a filled database and copy it over from the assets/-folder. See android-sqlite-asset-helper

Android: Why not make every method Synchronized?

Is there any downside to making every one of your methods synchronized in Android?
Yes - it will end up taking out locks when you don't really want them. It won't give you thread safety for free - it'll just slow down your code and make it more likely that you'll run into deadlocks due to taking out too many locks.
You need to think about thread safety and synchronization explicitly. I usually make most classes not thread-safe, and try to limit the number of places where I think about threading.
The "make everything synchronized" approach is a common one in what I think of as the four stages of threading awareness for developers:
Complete ignorance: no synchronization, no awareness of the potential problems
Some awareness, but a belief that universal synchronization cures all ills
The painful stage of knowing where there are problems, and taking a lot of care over getting things right
The mythical stage of getting everything right naturally
Most experienced developers are in stage 3 as far as I can tell - with different levels of ease within it, of course. Using immutability, higher-level abstractions instead of the low-level primitives etc helps a lot - but ultimately you're likely to have to think a fair amount whenever you've got multiple threads which need to share state.

producer consumer

i have an application which has a part where some variables are written and read at very high frequency.
Is there any need of a semaphores or locks(Data consistency is not a concern in this case).Is there any chance of application terminating or crashing.I dont want to get into threads,semaphores and stuff as it is a trivial part of application.
There is not nearly enough information in your question to give you an accurate answer, but in general - if you have multiple threads, and one produces data, one consumes it, then yes, you will need synchronization.
You could use a BlockingQueue, or just a simple synchronized object, whatever is appropriate in your case... but you will need some synchronization, or else you risk random hard-to-reproduce crashes.
This is even more important when dealing with multi-core systems, which are becoming popular now.

Pitfalls of Android applications

Are there pitfalls or the points to remember while programming for Android? I think the list will include topics on Multithreading, Persistent Storage, etc.
There are many things that could be said here.
The Android videos from Google I/O 2009 cover most of the aspects that should be kept in mind, when programming on Android. In fact, the http://android-developers.blogspot.com/ articles are the source, on which these presentations expand, and seeing them explained from some of the best Google engineers (and as a bonus you'll get a Q&A section) is a must for every Android developer, IMO.
Some of the things that could be mentioned:
Don't use floats, when you can achieve similar results with integers, because Android doesn't have native support for floating point values.
Use the debugging tools extensively, to optimize both performance and maintainability, and to avoid common pitfalls like ViewGroup redundancy in UI design, or unnecessary multiple calls to heavier methods (View.inflate(), findViewById(), setImageResource()).
Bundle your background service calls, otherwise you are waking up the OS unnecessarily and too often, while risking other services piggy-backing your call (which results in severely reduced battery life)
Prefer SAX-parsers over DOM-parsers, you lose time while implementing them, but you win time in your app's performance (and your device's availability)
Keep your UI manipulations on your UI thread, because the interface toolkit is not thread-safe
Keep in mind that orientation change destroys and creates your Activity again (I learned that the hard and painful way - this is how I started to follow the android-developers' blog)
...and many others.
Android Developers has good post about avoiding memory leaks due to keeping Context references. There are a lot of other interesting posts there too.
I wouldn't call them pitfalls per se, but always remember to take into account that this is not a computer that's plugged into a wall that can just be upgraded in various ways. You have an upgrade cycle of about every 2 years (the length of a standard mobile contract these days) and the hardware is (A) not the fastest and (B) static during that time.
Things to take into consideration:
1) How does the things your app does affect battery life? Are you splashing bright graphics all over the place? Running a lot of threads in the background? Services?
2) How much space does your application need to take up on the device? Is the information something that can be kept on a server and transmitted to the device for temporary use only when it's needed?
3) In regards to #2, is your app tolerant of bad/nonexistent network/mobile connections? How does it perform on the EDGE network vs 3G?
I'm sure you can come up with more but this is what I keep in mind while I'm writing my apps.

Categories

Resources