应用线程与服务线程 [英] Application threads vs Service threads

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

问题描述

将冗长的网络访问代码放置在活动中的线程或服务中的线程中有什么优点/缺点?对申请有什么影响?我正在编写一个流式音频播放器,从我到目前为止所读到的内容来看,将代码放入服务中最终仍会阻塞应用程序,因此需要一个新线程,有没有人知道放置这段代码是否更有意义在服务中.

What are the advantages/disadvantages in placing a lengthy network access code in a thread in an activity or a thread in a service? How would it affect the application? I am writing a streaming audio player and from what I've read so far putting the code in a service will still end up blocking the application so a new thread is needed, does anyone know if it makes more sense to put this piece of code in a service.

推荐答案

是的,Service 中的阻塞操作仍然会阻塞应用程序.尽管第一次出现,服务并不仅仅用于在后台运行任务.它们用于运行生命周期独立于 Activity 生命周期的任务(即,它们可能会在 Activity 关闭后继续).

Yes, a blocking operation in a Service will still block the application. Despite first appearances, Services are not simply for running tasks in the background. They are for running tasks with a lifecycle that is independent of the Activity lifecycle (IE, they may continue after the Activity is closed).

在Activity启动时启动并在Activity结束时结束的Service是无用的.

A Service that starts when an Activity starts and ends when the Activity ends is useless.

在您的情况下,您正在流式传输音频,即使在用户关闭 Activity 后,您也可能希望流式传输音频,在这种情况下,您应该使用服务,但您仍然需要一个线程(或 AsyncTask)用于阻塞任务.

In your case, where you are streaming audio, you may want to stream audio even after the user closes the Activity, in which case, you should use a Service, but you'll still need a thread (or an AsyncTask) for blocking tasks.

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

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