Skip to content Skip to sidebar Skip to footer

Android: Get Result From A Service

I have android service which I need to return a result after it has been started. So: 1) I start the service 2) The service does something 3) The service returns a result I thought

Solution 1:

This code you have in getInfo():

mInstanceContext.startService(myIntent);
//take the result
return (Integer) Result.getInstance().getResult();

assumes that when you call startService() the service is started and onStartCommand() is called synchronously so that in the next statement you can get the result using Result.getInstance().getResult().

Unfortunately, it doesn't work that way. Calling startService() isn't like calling a method on an object. What you do when you call startService() is that you tell Android that you want that service to be started at the next available moment. Since onStartCommand() in your service needs to be called on the main thread, usually this means that Android will start your service and call onStartCommand() at the next time when Android gets control of the main thread (ie: when all your activity methods have returned). In any case, you can't determine when the service will be started or when onStartCommand() will be called. It is an asynchronous call, so you need to rely on a callback mechanism. This means that you need to write some kind of callback method that the service can call when it has done the work and wants to return the result to you.

There are various ways to do this. You could have the service send an Intent to your activity. You could have the service broadcast an Intent with the results. You could bind to the service and register a callback listener (see developer documentation for bound services). There are probably other ways too.

Post a Comment for "Android: Get Result From A Service"