问题
What should I use to make an application that will:
- Ask the user for username and password
- Authorize
- 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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/39672466/service-vs-thread