user3677331
user3677331

Reputation: 698

Android Service taking up huge amount of memory

Here's how my application works: The Launcher activity starts a service in the foreground which monitors clipboard changes and fires up the launcher activity everytime a specific kind of string is copied. I'm new to Java programming, I've tried to use all the best practices in the application(using worker threads and keeping the UI thread from hiccupping) and so far everything is butter smooth. The problem is RAM consumption, on a fresh start of the app(after Service is started) the app reports 24M memory consumption in the android running processes. Here's where the erroneous behavior lies:

-adb shell command and Memory Monitor The Memory Monitor in Android Studio reports something else - So does the adb shell dumpsys meminfo mypackage command Screenshots of both have been attachedRunning Processes

These behaviors are incomprehensible for me. 50M is a lot of RAM. Also whenever the Launcher activity is launched by the Service, the app consumes around 1M more memory than it is already using. Can anyone help me debug this? Thanks

Upvotes: 4

Views: 4034

Answers (2)

lxgr
lxgr

Reputation: 3797

The problem is likely a result of how Android handles Services and Activities running in the same application process:

As long as a (started) Service is running in the process, the "memory priority" of the whole process is elevated above other processes that are only running (background) Activities.

However, since Activities are never recycled by Android even under memory pressure (contrary to some statements in the official docs), this effectively keeps your Activity alive much longer than necessary. This is essentially a shortcoming of Android's process model.

If your memory usage drops to a few megabytes after you force-kill your application process (and Android subsequently relaunches your Service), or if the memory usage is different depending on whether you leave your activity by pressing the home or back button, this confirms that you are facing this problem.

If you really depend on your Service continuously running in the background and want to minimize memory usage, you could try to move it to its own process (where memory-intensive UI resources like Views in Activities would never be loaded).

Of course, this also increases overhead; you might be better off by just keeping your implementation the way it is. Android will still kill your process under memory pressure, and will later relaunch your Service (but not your Activities), which will minimize your memory usage without any intervention.

Upvotes: 3

tim687
tim687

Reputation: 2276

Save the heapdump as a HPROF file and convert it to an extension that Java Profiler can read

Then you will be able to see what is using so much ram

Upvotes: 0

Related Questions