java - 服务或线程或异步任务

标签 java android android-asynctask android-service

请原谅我的问题,因为我对编程还很陌生,所以我不完全理解主线程、异步任务、服务和线程的概念。我正在阅读有关 Android 服务的文档,因为我想在主线程之外执行一些任务。它说:

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service.

1.他们是说“线程”在您离开应用程序后立即停止(即:主页按钮)吗?

For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.

2.如果Java中加入了线程,为什么android有AsyncTasks?

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

3.这是否意味着几乎每个服务基本上都会在其中创建一个线程?

4.在服务内部启动一个 AsyncTask 会不好吗?

最佳答案

1.Are they saying that a "thread" stops immediately after you leave the app (i.e: Home button)?

Thread 应该在启动它的 Thread 被销毁时被销毁。因此,如果您在 Activity 中启动一个 Thread,那么当 Activity 被销毁或转移到 Service< 时,它应该被销毁。例如,您可以在 Thread 中开始播放音乐并在那里更新歌曲,但是如果您希望它在 Activity 被销毁时继续播放,则应将其移至 服务

2.If threads are baked into Java, why does android have AsyncTasks?

AsyncTask 允许您执行后台工作,并通过使用其任何内置方法在后台工作完成之前、期间和之后轻松更新 UI doInBackground() 除外,因为它是唯一UI 线程

上运行的

3.Does this basically mean, that almost every service is basically going to have a thread created inside it?

不一定,但你可以在其中创建一个Thread

4.Would it be bad to start an AsyncTask inside of a service?

没有。你可以这样做。

AsyncTask是做后台工作的好方法。它的方法使更新 UI 变得非常容易。但是您需要仔细阅读文档(甚至可能多次)以确保您完全理解如何使用它们。另外,请记住,这些是用于短期操作的,因此它们可以很好地用于下载网络数据,但不应该用于持续超过几秒钟的操作(根据文档)

关于java - 服务或线程或异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17954383/

相关文章:

java - 我如何更改代码并使用 stream() 而不是函数式编程?

java - 如何一遍又一遍地运行 AsyncTask?

java - Android TCP 客户端。服务器仅在进程停止后接收消息

java - Android 应用程序随机崩溃(java.lang.NoClassDefFoundError)

java - Hudson 使用什么密码加密?

java - @queryparam 客户端赋值

java - 在 Java 8 上给定键列表从映射中提取值列表

Android JavaCV FFmpeg webstream 到本地静态网站

android - 在 Android 中显示 SVG 文件

android - 地理围栏 API : adding successful but not triggered