RAM (Random-access memory) is a crucial resource in the mobile application development environment, but it is even more crucial on a mobile operating system where physical memory is often constrained.

RAM (Random-access memory) is a crucial resource in the mobile application development environment, but it is even more crucial on a mobile operating system where physical memory is often constrained.

To maintain a functional multi-tasking app development environment, Android sets tough limits on the heap size for each mobile application. The exact heap size limit varies among devices based on how much random access memory the device has available overall. If your mobile app has reached the heaped capacity and tries to allocate more memory, it’ll receive an “OutOfMemory” error.

You can call getMemoryClass() to get an estimate of your mobile app’s available heap in megabytes. In very special situations, you can request a larger heap size by setting the large Heap attribute to “true” in the manifest <application> tag.

Stay Informed With latest News – Top Mobile App Trends in 2019

Never request a large heap simply because you have run out of memory and you need a quick fix— you should use it only when you know exactly where all your memory is being allocated and why it must be retained

android memory management


How Your Mobile Application Should Manage Memory?

You should consider RAM constraints throughout all phases of Android application development, including during app design (before you begin development). There are many ways you can design and write code that leads to more efficient results.

You can apply the below-mentioned techniques while designing and implementing your mobile application to make it more memory efficient.

1. If your app needs a service to perform work in the background, do not keep it running unless it’s actively performing a job. Also, be careful to never leak your service by failing to stop it when its work is done. The best way to limit the lifespan of your service is to use an IntentService, which finishes itself as soon as it’s done handling the intent that started it. Leaving a service running when it is not needed is one of the worst memory-management mistakes an Android application can make. So don’t be greedy by keeping service for your app running.

2. When the user navigates to a different app and your UI is no longer visible, you should release any resources that are used by only your UI. Releasing UI resources at this time can significantly increase the system’s capacity for cached processes, which has a direct impact on the quality of the user experience. To be notified when the user exits your UI, implement the onTrimMemory() callback in your Activity classes. You should use this method to listen for the TRIM_MEMORY_UI_HIDDEN level, which indicates your UI is now hidden from view and you should free resources that only your UI uses.


3. Avoid wasting memory with bitmaps. When you load a bitmap, keep it in RAM only at the resolution you need for the current device’s screen, scaling it down if the original bitmap is a higher resolution. Keep in mind that an increase in bitmap resolution results in a corresponding (increase2) in memory needed, because of both the X & Y dimensions increase.

4. Be aware of memory overhead.

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.
  • Every class instance has 12-16 bytes of RAM overhead.
  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes

5. Be careful about using external libraries. External library code is often not written for mobile environments and can be inefficient when used for work on a mobile client. At the very least, when you decide to use an external library, you should assume you are taking on a significant porting and maintenance burden to optimize the library for mobile. Plan for that work up-front and analyze the library in terms of code size and RAM footprint before deciding to use it at all.

6. Use ProGuard to strip out any unneeded code. The ProGuard tool shrinks optimize and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names.

7. Avoid Creating Unnecessary Objects

  • Object creation is never free. Allocating memory is always more expensive than not allocating memory.
  • If you have a method returning a string, and you know that its result will always be appended to a StringBuffer anyway, change your signature and implementation so that the function does the append directly, instead of creating a short-lived temporary object.
  • When extracting strings from a set of input data, try to return a substring of the original data, instead of creating a copy.
  • An array of ints is much better than an array of Integer objects.

8. Prefer Static Over Virtual

If you don’t need to access an object’s fields, make your method static. Invocations will be about 15%-20% faster. It’s also a good practice because you can tell from the method signature that calling the method can’t alter the object’s state.

Do You Feel Difficulty in Managing Memory Effectively? You Need an Expert Android Development Company


How to Improve Layout Performance?

Layouts are a key part of Android applications that directly affect the user experience. If implemented poorly, your layout can lead to a memory hungry application with slow UIs. For example, using nested instances of Linear Layout can lead to an excessively deep view hierarchy.

1. Re-using Layouts with <include/>

Reusing layouts is particularly powerful as it allows you to create reusable complex layouts.

2. Loading Views On Demand

Sometimes your layout might require complex views that are rarely used. Whether they are item details, progress indicators, or undo messages, you can reduce memory usage and speed up rendering by loading the views only when they are needed.


mobile app development


Memory Monitor in Android Studio

Use Android Studio to view your app’s memory use:

  • Start your app on a connected device or emulator.
  • Open the Android run-time window, and view the free and allocated memory in the Memory Monitor.
  • Click the Dump Java Heap icon () in the Memory Monitor toolbar.
  • Android Studio creates the heap snapshot file with the filename Snapshot-yyyy.mm.dd-hh.mm.ss.hprof in the Captures tab.
  • Double-click the heap snapshot file to open the HPROF viewer.
  • Note: To convert a heap dump to standard HPROF format in Android Studio, right-click a heap snapshot in the Captures view and select Export to standard .hprof.
  • Interact with your app and click the () icon to cause heap allocation.
  • Identify which actions in your app are likely causing too much allocation and determine where in your app you should try to reduce allocations and release resources.

Device Monitor

  • Open the Device Monitor.
  • From your <sdk>/tools/ directory, launch the monitor tool.
  • In the Debug Monitor window, select your app’s process from the list on the left.
  • Click Update Heap above the process list.
  • In the right-side panel, select the Help tab.

The Heap view shows some basic stats about your heap memory usage, updated after every GC. To see the first update, click the Cause GC button.

Figure: The Device Monitor tool, showing the [1] Update Heap and [2] Cause GC buttons. The Heap tab on the right shows the heap results.

Continue interacting with your app to watch your heap allocation update with each garbage collection. This can help you identify which actions in your app are likely causing too much allocation and where you should try to reduce allocations and release resources.


Hire Mobile App Developers on fixed cost, full time (dedicated monthly) or hourly basis at 60% less cost and also get ready-to-use infrastructure and expert Android full stack developers.


Tracking Allocations

As you start narrowing down memory issues, you should also use the Allocation Tracker to get a better understanding of where your memory-hogging objects are allocated. The Allocation Tracker can be useful not only for looking at specific uses of memory, but also to analyze critical code paths in an app such as scrolling.

For example, tracking allocations when flinging a list in your app allows you to see all the allocations that need to be done for that behaviour, what thread they are on, and where they came from. This is extremely valuable for tightening up these paths to reduce the work they need and improve the overall smoothness of the UI.

To use the Allocation Tracker, open the Memory Monitor in Android Studio and click the Allocation Tracker icon. You can also track allocations in the Android Device Monitor:

Android Studio

To use the Allocation Tracker in Android Studio:

  • Start your app on a connected device or emulator
  • Open the Android run-time window, and view the free and allocated memory in the Memory Monitor.
  • Click the Allocation Tracker icon () in the Memory Monitor toolbar to start and stop memory allocations.
  • Android Studio creates the allocation file with the filename Allocations-yyyy.mm.dd-hh.mm.ss.alloc in the Captures tab.
  • Double-click the allocation file to open the Allocation viewer.
  • Identify which actions in your app are likely causing too much allocation and determine where in your app you should try to reduce allocations and release resources.

Device Monitor

  • Open the Device Monitor.
  • From your <sdk>/tools/ directory, launch the monitor tool.
  • In the DDMS window, select your app’s process in the left-side panel.
  • In the right-side panel, select the Allocation Tracker tab.
  • Click Start Tracking.
  • Interact with your app to execute the code paths you want to analyze.
  • Click Get Allocations every time you want to update the list of allocations.

The list shows all recent allocations, currently limited by a 512-entry ring buffer. Click on a line to see the stack trace that led to the allocation. The trace shows you not only what type of object was allocated, but also in which thread, in which class, in which file and at which line.

download (1)

Figure: The Device Monitor tool, showing recent app allocations and stack traces in the Allocation Tracker.

Note: You will always see some allocations from DdmVmInternal and elsewhere that come from the allocation tracker itself.

Although it’s not necessary (nor possible) to remove all allocations from your performance critical code paths, the allocation tracker can help you identify important issues in your code. For instance, some apps might create a new Paint object on every draw. Moving that object into a global member is a simple fix that helps improve performance.

Capturing a Heap Dump

A heap dump is a snapshot of all the objects in your app’s heap, stored in a binary format called HPROF. Your app’s heap dump provides information about the overall state of your app’s heap so you can track down problems you might have identified while viewing heap updates.

To retrieve your heap dump from within Android Studio, use the Memory Monitor and HPROF viewer.

You can also still perform these procedures in the Android monitor:

  • Open the Device Monitor.
  • From your <sdk>/tools/ directory, launch the monitor tool.
  • In the DDMS window, select your app’s process in the left-side panel.
  • Click Dump HPROF file, shown in figure 3.
  • In the window that appears, name your HPROF file, select the save location, then click Save.

Memory_management_in_android.doc Google Docs

Figure 3. The Device Monitor tool, showing the [1] Dump HPROF file button.

If you need to be more precise about when the dump is created, you can also create a heap dump at the critical point in your app code by calling dumpHprofData().

The heap dump is provided in a format that’s similar to, but not identical to one from the Java HPROF tool. The major difference in an Android heap dump is due to the fact that there are a large number of allocations in the Zygote process. But because the Zygote allocations are shared across all app processes, they don’t matter very much to your own heap analysis.

To analyze your heap dump, you can use Memory Monitor in Android Studio. You can also use a standard tool like that. However, first, you’ll need to convert the HPROF file from Android’s format to the J2SE HPROF format. You can do this using the hprof-conv tool provided in the <sdk>/platform-tools/ directory. Simply run the hprof-conv command with two arguments: the original HPROF file and the location to write the converted HPROF file. For example:

hprof-conv heap-original.hprof heap-converted.hprof

You can now load the converted file into a heap analysis tool that understands the J2SE HPROF format.

When analyzing your heap, you should look for memory leaks caused by:

  • Long-lived references to an Activity, Context, View, Drawable, and other objects that may hold a reference to the container Activity or Context.
  • Non-static inner classes (such as a Runnable, which can hold the Activity instance).
  • Caches that hold objects longer than necessary.

Hire android developers on fixed cost, full time (dedicated monthly) or hourly basis at 60% less cost and also get ready-to-use infrastructure and expert Android full stack developers.