In our Android app, we have UI component and core C++11 module. A thread is running based on std::chrono::system_clock::time_point
, such as below:
When the device is idle, the CPU is stopped and any thread running is paused (C++ or Java). If it wakes up for any reason your C++ thread will start working again, hence the random behavior: Other apps or services might wake-up the device every now and then.
Adding a partial wake lock works in your case but that will prevent the CPU from going idle, which will cause some battery drain. If you don't care you can use this approach, if battery live is an issue, you can use the Java alarm API to wake up the device on a regular basis. Then the java API can call the C++ code through JNI.
Android documentation for repeated alarms: https://developer.android.com/training/scheduling/alarms.html
For the update 3, using a small sleep rather than wait()
, I suspect android is not going in idle mode while a thread is running, maybe it waits for a small timeout without any thread active before it goes idle. This approach will have the same effect on the battery drain than the wake lock.