So, I’ve a
Service that is important for applications logic and thus needs to be alive all the time.
First thing is first, I created it as a
Whenever user starts to run,
Service starts to do a lot of heavy things. It uses
FusedLocationAPI different type of sensors and do a lot of different calculations. At this point phone starts to heat up (CPU usage is high). When running stops, heating stops and CPU drops lower.
This makes me think that the main problem is whenever these sensors are used and calculations are made, but there’s a lot of possibilities that could cause this and I wanted to understand, how can I deeply analyze batter usage in this case? I read that
Battery Historian should be way to go, but the information there is complicated and do not give me much information. How can I use this data to understand which class/runnable/code part is held responsible for the CPU usage? Maybe there’s better ways to solve this? Thanks in advance.
Detailed analysis on what’s happening using CPU profiler (after suggestion).
- Image. Application is opened and few different screens are switch to and from. Nothing special. Phone does not heat up and from CPU analysis everything also looks pretty okay.
2.User starts to run and enter heavy state. The yellow (light green) rectangle shows previously mentioned “important service” that bring important role to application. Called functions does not use too much time of CPU considering the % of whole running trip – which makes me think, I’ve to look somewhere else..
- What I saw is that CPU increases heavily whenever I lock the phone (while service is running. From CPU
Bottom Upanalysis I cannot understand what is causing the problem (orange rectangle) – looks like a bunch of Android stuff is happening, but it does not give me any clue.
From CPU profiler I do understand that I have a serious problem considering CPU usage, but right now I do not understand what is causing it (which piece of code/class/function). I know for the fact that whenever my important service is created (on app start) I use
PARTIAL_WAKE_LOCK to not allow CPU go to sleep and also make service to be alive at all times. As I understand I need to find different solution for this, because CPU drains too much of battery.
How could I found this using only profiler? I now this fact only for code and profiler stack does not tell me much about this (maybe Im not looking at the right place?)
I found out the root cause of high CPU usage.
I did detailed investigation on threads and found out that
DefaultDispatcher threads are using A LOT of CPU.
Turns out the has been a bug in Kotlin-Coroutines library and latest version provides fixes. When I did tests I used version
1.3.1, but changing version number to
1.3.3 provided me with big improvements: from 40% usage to 10% CPU usage.