服务与线程 [英] Service vs Thread

查看:29
本文介绍了服务与线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该用什么来制作一个应用程序:

What should I use to make an application that will:

  1. 向用户询问用户名和密码
  2. 授权
  3. 运行一个无限循环,每 10 秒左右从网站获取一些数据.
  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.

我还想问:服务和线程一样容易交互吗?我可以在其中传递一个 CancellationToken 并在用户按下停止按钮时取消它吗?

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?

我还找到了 setThreadPriority,这对我有帮助吗?

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

推荐答案

服务和线程是完全不同的概念.线程是并行执行的独立进程.服务是应用程序的一个组件,它没有 UI 并以单独的生命周期运行.服务不在自己的线程上运行,而是在 UI 线程上运行(尽管它可以根据需要启动一个线程).

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).

如果您想执行某些任务但又不想绑定到 Android Activity 生命周期,则可以使用 Service.如果要并行运行,请使用线程.如果两者都需要,那么您可以使用启动线程的服务.

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.

从我读到的内容(您不希望 Activity 在 Activity 完成后继续执行),您需要的是 Thread 而不是 Service.

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.

这篇关于服务与线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆