1

My requirement is simple.

I have a simple app. 2 Buttons. and 1 service. Conditions: Button1 clicked,-> Start the IntentService.Button2 clicked -> Stop the IntentService.

The first part works fine. I can start the IntentService using startService(intent) command. However, I cannot stop the IntentService. i.e., stopService(intent) command isn't working. It is neither throwing an error nor doing anything.

Can anyone please shed some light on this??

I searched and found this question How to stop an IntentService? but it doesn't answer my need.

Community
  • 1
  • 1
Android_Noob
  • 487
  • 2
  • 6
  • 19
  • Do you need to do async work in your intentservice? – greywolf82 Jan 18 '15 at 13:40
  • Yes. I want a service to run in background for infinite time untill User wants to stop it. ( By clicking a button in my case). – Android_Noob Jan 18 '15 at 14:22
  • 1
    I don't think you understand how `IntentService` works. You call `startService()` and pass an `Intent` which contains enough information for the service to know what to do. The service starts and does whatever it should do and then, if it has no more work to do (ie: no more queued `Intent`s), it stops itself. It doesn't run again until another call to `startService()`. So can't stop an `IntentService` if it is currently processing an `Intent`, and if it isn't currently processing something, it isn't running anyway. – David Wasser Jan 18 '15 at 22:59

3 Answers3

1

You can't stop an IntentService manually. An IntentService will stop itself automatically, when there are no more intents for that service to process.

If you want to stop a service by clicking a button, use a normal Service.

max59
  • 606
  • 1
  • 7
  • 16
  • Okay... Thank you. Could you please tell me how can I re-Start an IntentService after a delay of say 10 seconds? The thing is I have an infinite loop running in it but if the User wants to stop the service, he should be. Is there a way to add some permission in manifest to achieve this with IntentService? or anything ? – Android_Noob Jan 18 '15 at 14:16
1

I figured it out. We cannot stop an IntentService till it completes all the steps in the process.

However, we can place an intermediary check Ex: if(boolean continue == true){then do next}.esle {stopSelf(); } And we can change the value of 'continue'to false and instead of 'StopService' command.

Hope it helps someone who has similar problem like me.. :-)

Android_Noob
  • 487
  • 2
  • 6
  • 19
1

However, you cannot kill the IntentService. The service will stop automatically after all of thread queues completed. Though you call MyIntentService.this.stopSelf(); from Activity, the service will stops, but the thread still running in background process.

Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87