Java – Android services take up a lot of memory

Android services take up a lot of memory… here is a solution to the problem.

Android services take up a lot of memory

Here’s how my app works:
The Launcher activity starts a service in the foreground that monitors clipboard changes and starts the launcher activity each time a specific type of string is copied. I’m new to Java programming and I’ve tried to use all the best practices in my application (using worker threads and preventing UI thread hiccups) and so far everything has gone very well. The problem is RAM consumption, when the application restarts (after the service starts) the application reports 24M memory consumption in the android running process. This is where the error is:

adb shell command and memory monitor Memory Monitor in Android Studio reports other content
The same goes for the adb shell dumpsys meminfo mypackage command
Screenshots of both are attached< img alt="Running Processes" src="http://res.cloudinary.com/dfrkaf37y/image/upload/v1671510588/etbye/38uF7.png"/>

These behaviors are incomprehensible to me. 50M is a lot of RAM. In addition, whenever the service starts a Launcher activity, the application consumes 1M more memory than it already uses. Can anyone help me debug this?
Thanks

Solution

The question may be how Android handles services and services
Activities running in the same application process:

As long as there is one (started) service running in the process, “memory.”
The priority of the whole process” is elevated above other processes
Only run (background) activities.

However, due to Activity
are Never recycled Android Even under memory pressure (with
some statements in the official documentation),
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 forcibly terminate your application process (and Android subsequently restarts your service), or if memory usage varies depending on whether you leave the activity by pressing the Home or Back buttons, this confirms that you are facing this issue.

If you really rely on your service to run continuously in the background and want to minimize memory usage, you can try moving it to its own process (where memory-intensive UI resources such as View in an activity are never loaded).

Of course, this also adds overhead; It might be better to leave the implementation as it is. Android will still terminate your processes under memory pressure and later restart your services (but not your activities), which will minimize your memory usage without any intervention.

Related Problems and Solutions