I have an IntentService
that starts an asynchronous task in another class and should then be waiting for the result.
The problem is that the IntentService
will finish as soon as the onHandleIntent(...)
method has finished running, right?
That means, normally, the IntentService
will immediately shut down after starting the asynchronous task and will not be there anymore to receive the results.
public class MyIntentService extends IntentService implements MyCallback { public MyIntentService() { super("MyIntentService"); } @Override protected final void onHandleIntent(Intent intent) { MyOtherClass.runAsynchronousTask(this); } } public interface MyCallback { public void onReceiveResults(Object object); } public class MyOtherClass { public void runAsynchronousTask(MyCallback callback) { new Thread() { public void run() { // do some long-running work callback.onReceiveResults(...); } }.start(); } }
How can I make the snippet above work? I've already tried putting Thread.sleep(15000)
(arbitrary duration) in onHandleIntent(...)
after starting the task. Itseems to work.
But it definitely doesn't seem to be clean solution. Maybe there are even some serious problems with that.
Any better solution?
This class was deprecated in API level 30. IntentService is subject to all the background execution limits imposed with Android 8.0 (API level 26). Consider using WorkManager or JobIntentService , which uses jobs instead of services when running on Android 8.0 or higher.
What is IntentService in Android? IntentService in Android is a base class for Services to handle asynchronous requests that are expressed in the form of Intents when there is a demand to do so. The requests are sent by the clients through Context. startService(Intent) calls to start the service.
Start a service. An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method. // use this to start and trigger a service Intent i= new Intent(context, MyService. class); // potentially add data to the intent i.
Use the standard Service
class instead of IntentService
, start your asynchronous task from the onStartCommand()
callback, and destroy the Service
when you receive the completion callback.
The issue with that would be to correctly handle the destruction of the Service
in the case of concurrently running tasks as a result of the Service
being started again while it was already running. If you need to handle this case, then you might need to set up a running counter or a set of callbacks, and destroy the Service
only when they are all completed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With