简体   繁体   English

使用AsyncTask或Service从服务器下载视频

[英]Use AsyncTask or Service to download video from server

I want to download a video (mpeg) from my server and need to save it on the SD card. 我想从服务器下载视频(mpeg)并将其保存在SD卡上。 Is it bettet to use an AsyncTask or a Service ? 使用AsyncTask还是Service是更好的选择?

Could you give me a concept of when to use which? 您能给我一个什么时候使用的概念吗?

Android provides a DownloadManager class which will handle background downloads with minimal effort. Android提供了一个DownloadManager类,该类将以最小的努力处理后台下载。

dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri))
        .setDestinationInExternalFilesDir(getContext(), "downloads", "myVideo.avi");
int downloadId = dm.enqueue(request);

By persisting downloadId it lets you cancel the download and it will also notify you upon completion with a broadcast. 通过持久保留downloadId它可以使您取消下载,并且还可以在广播完成时通知您。 If needed, you can even query for progress. 如果需要,您甚至可以查询进度。

Have a look at the documentation here . 这里查看文档。

(1) If you just have to download it and save it to sd card and no other thing to do with it or if it is a very large video file use and doesn't require frequent interaction with UI thread Intent Service (1)如果您只需要下载它并将其保存到sd卡中,而无需任何其他操作,或者它使用的视频文件非常大,并且不需要与UI线程Intent Service进行频繁交互,

(2) If it is a very small video file, use async task. (2)如果视频文件非常小,请使用异步任务。

(3) else if it is not too large use normal service (3)如果不是太大,请使用普通服务

It actually depends on your need. 这实际上取决于您的需要。

if your download needs to update any UI/UX content after successful downloading then please go ahead to use AsyncTask. 如果成功下载后下载文件需要更新任何UI / UX内容,请继续使用AsyncTask。

If that is not your case then please use the Service class by launching a separate Thread process inside it or you can also use IntentService. 如果不是您的情况,那么请通过在服务类中启动一个单独的Thread进程来使用Service类,或者您也可以使用IntentService。

That depends on your need like 这取决于您的需要
Async 异步
1. task is used to run when button is clicked. 1.任务用于单击按钮时运行。
2. Async task used for one time use. 2.一次使用异步任务。
Services 服务
1. You may use Service if you want to download continuously from server like download images whenever new came in server. 1.如果要从服务器中连续下载服务器,例如每当服务器中有新镜像时就下载映像,则可以使用服务。
2. Services executes in background continuously. 2.服务在后台连续执行。

It is faster to use Async task if you have to done task once per click or other on events. 如果您必须在每次单击或其他事件上一次完成任务,则使用异步任务会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM