I know that the code in onStartCommand will run on the main thread.
Inside this method I spawn a new network thread, that communicates with a server and when it finishes it executes a call back method that also runs in the main thread.
My question is, if both methods onStartCommand and the callback method are executed in the main thread, and the call back method is executed whenever the network call finishes, is it possible that lines of code of the call back method are executed in the middle of the execution of the onStartCommand method?
How does this work?
If the spawned network thread makes a function call that you are certain will execute in the main thread, then the only way to achieve this is by some sort of shared resource, the most common being: some sort of work queue, a socket, or a variable shared between the two threads (set via a method call) that would have to be polled by the main thread causing it to execute a certain method.
I would think the easiest way would be a work-queue, but according to the link you posted in your comments, it mentions JSON which typically uses a TCP/IP socket. I’ll cover how each method typically works.
Work Queue:
The network thread will create some sort of work entry and enqueue it on the main thread work queue. If the main thread is in the middle of a method (onStartCommand()) then it cant also execute the work entry. Most likely when it finishes the current method it will return and get back to a polling method that pulls entries off the queue. So if this approach is used, then onSuccess() and onFailure() will create and enqueue work entries that will be executed after returning from onStartCommand()
JSON Socket:
This approach is very similar to the Work Queue, but instead of work entries, socket messages will be used. And there will be a function that will poll (most likely via select() or poll()) the socket and treat the received messages as work items. So if this approach is used, then onSuccess() and onFailure() will create and send socket messages that will be executed after returning from onStartCommand()