GPS GPS - 1 month ago 10
Android Question

Thread scheduling issue with Android service

I have a driver (Android HAL) and a service that communicate with each other through unix socket. They both have a thread to maintain connection using heartbeat. HAL is socket daemon and service is socket client.

HAL loads on boot. Service loads when an app binds to it. This app doesn't do anything else.

I observe that as long as App is visible, both client and daemon threads are fine. But when I push app to background (e.g. by pressing home button) I observe a bunch of timeouts in client thread reported by daemon thread (because heartbeat is not sent fast enough).

I did some timing measurements and found that as long as app is visible, Service behaves correctly, but when app is invisible, service thread behaves erratically. It's almost as if scheduler is not executing thread in service often enough.

At this time, there is no other apps on Android system.

This behavior was verified with Nexus 7 (2013) and Nexus 5X running M and Nexus Player running Android N

If app starts service, instead of binding to it, Bad thread scheduling persists. Only difference is that, now App visibility state does not effect service thread execution (it's always slow.)

Is there a way to make service thread run faster?

primarily, the thread just does a select() call for 10ms, followed by some book-keeping in a loop. psuedo-code as follows:

while(running) {
if not_connected {
connect()
}
if send_heartbeat_timeout_elapsed
send_heartbeat()
}
if recv_heartbeat_timeout_elapsed {
close_connection()
}
if connected {
wait_for_daemon_msg(10 ms)
if msg_received {
process_msg()
}
}
}


Edit 1:
Perhaps it is useful to mention, In final system, I need to be able to "start" service on boot, and there shall be no app. I need Service threads to execute properly in this scenario.

Edit 2:
Found that if I make my service a "foreground service", this scheduling issue subsides.

I am baffled by the fact that a Service process' priority is not sufficient to allow it to execute often enough, even during otherwise low cpu loads. Ideally I shouldn't need to do this.

Leaving question open for now, in case a useful answer pops up.

GPS GPS
Answer Source

As long as I need my service to perform in a timely fashion, I create and keep a notification icon.

This helps on both phone/tablet versions and Android TV versions, even though TV doesn't show notification icons. When icon is removed from notifications, service becomes slow.

I later had thought about this, and realised that there are probably no services that need to do background tasks in timely fashion, but don't also have a notification icon/controls. E.g. music players that play in background will typically leave controls in a notification.

If someone finds a better solution, please bring it to light.