I have an Android Service running in a separate process from its client, and is running only as long as the client is connected. I am wondering when exactly during its lifecycle does it accept requests from the client?
I am having problems with requests that are made early / late in the Service’s lifecycle. As far as I understand, each request is handled in a thread separate from the main Service thread. I have the following problems:
- A request is handled by the Service before or during the Service.onCreate(). I have seen exceptions that are trying to use resources that are initialized in my Service.onCreate(), but these are null, and logging confirms that the main Service thread is in the onCreate().
- A request is handled by the Service during or after the Service.onDestroy(). Again, exceptions and logging have confirmed that a thread is handling a request and trying to use resources that have been released in the onDestroy().
Is it possible for Android to allow requests to be made to a Service that isn’t completely initialized or destroyed?
Please don’t do this, unless these processes represent separate apps.
“Request” is a meaningless term. I am assuming that by “request” you mean “call a method exposed by the
Binderpublished by the service”.Calls made to methods exposed by the
Binderare called on threads from a thread pool, separate from the main application thread. It’s one of the few places in Android where Android calls your code from a separate thread.This should be impossible, as
onBind()will not have been called yet, so there is noBinder. Nothing can make a “request” yet.I can’t rule out this possibility. I would have thought that Android would have torn down the IPC interface before
onDestroy()is called.It is “available” when the client’s
ServiceConnectionis called withonServiceConnected(). This will occur afteronCreate()andonBind()if the service did not already exist.