RockNRollStar
RockNRollStar

Reputation: 13

Android: How to stop Thread.sleep in an IntentService from the MainActivity

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.

Upvotes: 1

Views: 1122

Answers (2)

Eugene
Eugene

Reputation: 60184

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.

Upvotes: 0

Patrick W
Patrick W

Reputation: 1567

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.

Upvotes: 1

Related Questions