sooqua
sooqua

Reputation: 438

Service vs Thread

What should I use to make an application that will:

  1. Ask the user for username and password
  2. Authorize
  3. Run an infinite loop in which it will fetch some data from the website every 10 seconds or so.

I want to be able to do some basic tasks in the meantime, or lock my screen without the thread getting killed. I don't want the service to continue running after I close the application, I just want to be sure the thread is never killed while it's running for a long time.

I also wanted to ask: Are services as easy to interact with as threads? Can I just pass a CancellationToken in it and cancel it when the user presses the stop button?

I also found the setThreadPriority, will it help in my case?

Upvotes: 0

Views: 225

Answers (2)

GPRyan
GPRyan

Reputation: 455

A service can run in isolation (while your app is not necessarily running). A thread can be spun off from either your app itself, or a service.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93678

Services and Threads are totally different concepts. A Thread is a separate process that executes in parallel. A Service is a component of an app that doesn't have a UI and runs with a separate life cycle. A service does not run on its own thread, it runs on the UI thread (although it can launch a Thread if it wishes).

You use a Service if you want to do some task but not be bound to the Android Activity lifecycle. You use a Thread if you want to run in parallel. If you want both, then you use a Service that launches a Thread.

From what I'm reading (you don't want the Thread to continue after the Activity is finished), you want a Thread and not a Service.

Upvotes: 2

Related Questions