0

The first application that I'm developing in Android involves BLE scanning in background. The application has two buttons to start the service (which makes the scan and logs the results) and to stop the service.

From the documentation I learned the differences between Service and IntentService. I suspected that using an IntentService wouldn't be the best approach since the Android system destroys the service when all the intents delivered to it are handled and therefore the scanning running in the work thread created by the service would also stop working. However, I wanted to give it a try to test my knowledge.

As I was expecting, the service is almost immediately destroyed after it is created. However, the logs informing about new devices detected keep on appearing, which means that the scanning process keeps working even when the service is destroyed. When I close the main activity the scan finally stops. I want to know why the scan process seems to be bound to the thread of the main activity and not to the thread (automatically) created by the intent service. Why the scan process keeps working even when the service has been destroyed?

I have found some SO answers related with services and BLE scanning (here and here), but no one addressing this specific topic. Could you give me some help?

Community
  • 1
  • 1

1 Answers1

2

Per the Process Priorities blog post:

Android doesn’t go killing things just for the sake of killing things (remember: starting things from scratch isn’t free!), so these processes can potentially stay around for some time before being reclaimed due to memory needs from anything in a higher category, killed in order of least recent usage (oldest is reclaimed first).

Therefore even though your Service has been stopped, your process can stay in memory for some time. Since you haven't specifically stopped your BLE scanning on onDestroy, that work continues until your process is killed to reclaim the memory.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Thanks for your answer. Maybe I don't understand the difference between threads and processes. I understand that my process can stay alive even when one of my components has been destroyed (a service, for example). But I can not understand how a task which has been programmed to be executed in a specific thread can stay being executed even when the thread has been destroyed (which is what happens when the service is destroyed). I understand threads and processes as different concepts. – mikemontilla May 03 '17 at 21:00
  • Per the [BluetoothLeScanner source code](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/bluetooth/le/BluetoothLeScanner.java#382), it delivers results on the main thread - just because you register for scan results in `onHandleIntent`'s background thread does not tie the callback to that thread. – ianhanniballake May 03 '17 at 21:10