使用AsyncTask或Service在后台上传文件更好吗? [英] Is it better to use AsyncTask or Service to upload a file in background?

查看:21
本文介绍了使用AsyncTask或Service在后台上传文件更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求用户能够将视频上传到 Amazon S3.我已经使用亚马逊 sdk 中的 java 高级 api 实现了这一点.在上传过程中,如果用户点击主页按钮,上传必须在后台继续.

I have a requirement where a user is able to upload a video to Amazon S3. I have achieved this using the java high-level api in amazon sdk. During the upload process if the user clicks the home button the upload must continue in the background.

什么是更好的方法:?

*1 使用 AsyncTask:我尝试过使用 AsyncTask,它工作正常.但是如果上传过程在后台持续很长时间,操作系统会杀死应用程序以释放内存.有什么办法可以处理这种情况,让我的应用程序完成上传过程.

*1 Using AsyncTask: I have tried using AsyncTask and it works fine. But if the uploading process continues for long interval at the background, the OS kills the app to free memory. Is there any way that i can handle this situation, and let my app complete the upload process.

*2 使用服务:有人建议我使用服务 + ui 通知.我喜欢使用 AsyncTask,因为它对我来说很好用.与 AsyncTask 相比,使用 Service 有什么优势.

*2 Using Service: Someone suggested me to use a Service + ui notification. I feel like using AsyncTask, because it works fine for me. Is there any advantage of using a Service over AsyncTask.

推荐答案

大多数情况下,AsyncTask 与您的 UI、启动它的 Activity 等相关联.这些将保留在内存中,直到任务完成.

Most of the time an AsyncTask is coupled to your UI, the Activity that started it etc. Those will stay in memory until the task is finished.

您的这个上传场景需要通过 IntentService 来实现.这将使上传与特定活动分离,并使您的应用程序在 Android 生命周期方面成为良好的 Android 公民.

This upload scenario of yours begs for implementation through an IntentService. This will decouple the uploading from a specific activity and make your App a good Android citizen in regard to the Android life cycle.

您现在可以创建一个通知,该通知会从服务中定期更新,显示上传状态并让用户从其状态栏中取消上传.

You can now create a Notification that is periodically updated from the Service that shows the status of the upload and lets the user cancel the upload from his status bar.

这篇关于使用AsyncTask或Service在后台上传文件更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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