Service vs Thread

☆樱花仙子☆ 提交于 2020-01-17 05:38:55

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!