Android: C++ thread not waking up if screen-locked or in background. Works fine when app is in use

后端 未结 1 1894
失恋的感觉
失恋的感觉 2021-01-19 10:00

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:



        
相关标签:
1条回答
  • 2021-01-19 10:18

    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.

    0 讨论(0)
提交回复
热议问题