Question

I have a user login screen. The user presses a login button and I create an IntentService to connect to my rest services and return back a authentication result.

Now here's the functionality I want to achieve: If the activity is paused (i.e. goes into the background) then the intent service should still run, and it does. But if I use the task manager to kill the application, the intent service should stop, although right now it doesn't. It continues executing onHandleIntent until complete. If I manually call stopSelf(), onDestroy() is called but the onHandleIntent method continues to execute. How do I force the onHandleIntent to stop? Calling "return" is not an option because it could be caught up in one rest method call.

Should I be using intent service for this functionality or something else (like service or asynctask)?

Was it helpful?

Solution

First off, if your service is doing something that you want done while your app is running in the foreground, then you don't need a Service. Your activity or dialog can just spawn a thread to do your task, and these threads will end when your app ends, since they are within the task scope of your app. Otherwise, for tasks you want done all the time, when the user could be doing anything on the device, definitely use a Service.

I'm not sure why "calling return" is not an option for you? By this I assume you mean checking for a condition, and exiting the loop or block if the condition is met. This is generally how threads (in services or elsewhere) should end (although there are other approaches). Your service's thread can listen to a specific event that has occurred (like if the activity has been destroyed, by setting a property in a file or database when the activity's onDestroy is called, though if this is what you want then you probably should NOT use a Service), and then run() can return gracefully.

But if this is a task you want done no matter what the user is doing on his device (within or outside of your app), then it should be a task that should not be interrupted from the outside. It should keep going until it's done.

Maybe if you could better define when you want this service to be stopped?

OTHER TIPS

stop it in your onDestroy() method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top