1

I am developing an Android App. I have a MainActivity class where I launch an IntentService.

In the IntentService class, I use Thread.sleep in the method onHandleIntent to handle a necessary pause.

Everything works fine.

What I would like to do is have a button in the MainActivity UI which can interrupt the Thread.sleep in the IntentService.

Is this possible? Thank you.

Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
  • Do you have Some code? – Skynet May 05 '15 at 07:20
  • i think you cant do anything when intentservice already run – Randyka Yudhistira May 05 '15 at 07:24
  • Thank you. That was what I thought, but couldn't find it written down clearly enough for me. If I could vote, I would give patwanjau the points. – RockNRollStar May 05 '15 at 18:49
  • Skynet - the code would be too long, but it's simply a MainActivity class that launches an IntentService when a button is pressed. The IntentService has a method onHandleIntent, in which I call Thread.sleep. I'd like to make it sleep for a minute or two, but to let the user 'interrupt' the thread.sleep when they press a cancel button in the UI. I'll do it a different way... – RockNRollStar May 05 '15 at 18:52

2 Answers2

1

No, it's not possible. You cannot handle non UI related threads from the main UI thread. A thread is an independent entity when it's executed. If you want to be able to cancel a task that is already running, you should consider using AsyncTask and implement the doInBackground() method. Thereafter, it's possible to cancel this task from the UI if it's still executing.

Patrick W
  • 1,485
  • 4
  • 19
  • 27
0

Try to consider using a Service instead of the IntentService. The first one doesn't stop automatically, meaning it will listen to your commands you could send to it (I would go with EventBus) unless it is destroyed by the system to reclaim resources. Still you should definitely stop it on your own after you don't need it.

Anyways, I would better implement start/pause feature to control your flow rather than rely on thread interruptions.

Eugene
  • 59,186
  • 91
  • 226
  • 333