最近开发中遇到需要下载文件的问题,对于一般的下载来说不用考虑断点续传,不用考虑多个线程,比如下载一个apk之类的,这篇文章讨论的就是这种情形。

这里主要讨论三种方式:AsyncTask、Service和使用DownloadManager。

一、使用AsyncTask并在进度对话框中显示下载进度

这种方式的优势是你可以在后台执行下载任务的同时,也可以更新UI(这里我们用progress bar来更新下载进度)

下面的代码是使用的例子// declare the dialog as a member field of your activity

ProgressDialog mProgressDialog;

// instantiate it within the onCreate method

mProgressDialog = new ProgressDialog(YourActivity.this);

mProgressDialog.setMessage("A message");

mProgressDialog.setIndeterminate(true);

mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

mProgressDialog.setCancelable(true);

// execute this when the downloader must be fired

final DownloadTask downloadTask = new DownloadTask(YourActivity.this);

downloadTask.execute("the url to the file you want to download");

mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

@Override

public void onCancel(DialogInterface dialog) {

downloadTask.cancel(true);

}

});

DownloadTask继承自AsyncTask,按照如下框架定义,你需要将代码中的某些参数替换成你自己的。// usually, subclasses of AsyncTask are declared inside the activity class.

// that way, you can easily modify the UI thread from here

private class DownloadTask extends AsyncTask {

private Context context;

private PowerManager.WakeLock mWakeLock;

public DownloadTask(Context context) {

this.context = context;

}

@Override

protected String doInBackground(String... sUrl) {

InputStream input = null;

OutputStream output = null;

HttpURLConnection connection = null;

try {

URL url = new URL(sUrl[0]);

connection = (HttpURLConnection) url.openConnection();

connection.connect();

// expect HTTP 200 OK, so we don't mistakenly save error report

// instead of the file

if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {

return "Server returned HTTP " + connection.getResponseCode()

+ " " + connection.getResponseMessage();

}

// this will be useful to display download percentage

// might be -1: server did not report the length

int fileLength = connection.getContentLength();

// download the file

input = connection.getInputStream();

output = new FileOutputStream("/sdcard/file_name.extension");

byte data[] = new byte[4096];

long total = 0;

int count;

while ((count = input.read(data)) != -1) {

// allow canceling with back button

if (isCancelled()) {

input.close();

return null;

}

total += count;

// publishing the progress....

if (fileLength > 0) // only if total length is known

publishProgress((int) (total * 100 / fileLength));

output.write(data, 0, count);

}

} catch (Exception e) {

return e.toString();

} finally {

try {

if (output != null)

output.close();

if (input != null)

input.close();

} catch (IOException ignored) {

}

if (connection != null)

connection.disconnect();

}

return null;

}

上面的代码只包含了doInBackground,这是执行后台任务的代码块,不能在这里做任何的UI操作,但是onProgressUpdate和onPreExecute是运行在UI线程中的,所以我们应该在这两个方法中更新progress bar。

接上面的代码:

@Override

protected void onPreExecute() {

super.onPreExecute();

// take CPU lock to prevent CPU from going off if the user

// presses the power button during download

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,

getClass().getName());

mWakeLock.acquire();

mProgressDialog.show();

}

@Override

protected void onProgressUpdate(Integer... progress) {

super.onProgressUpdate(progress);

// if we get here, length is known, now set indeterminate to false

mProgressDialog.setIndeterminate(false);

mProgressDialog.setMax(100);

mProgressDialog.setProgress(progress[0]);

}

@Override

protected void onPostExecute(String result) {

mWakeLock.release();

mProgressDialog.dismiss();

if (result != null)

Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();

else

Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();

}

注意需要添加如下权限:

二、在service中执行下载

在service中执行下载任务的麻烦之处在于如何通知activity更新UI。下面的代码中我们将用ResultReceiver和IntentService来实现下载。ResultReceiver允许我们接收来自service中发出的广播,IntentService继承自service,这IntentService中我们开启一个线程开执行下载任务(service和你的app其实是在一个线程中,因此不想阻塞主线程的话必须开启新的线程)。public class DownloadService extends IntentService {

public static final int UPDATE_PROGRESS = 8344;

public DownloadService() {

super("DownloadService");

}

@Override

protected void onHandleIntent(Intent intent) {

String urlToDownload = intent.getStringExtra("url");

ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");

try {

URL url = new URL(urlToDownload);

URLConnection connection = url.openConnection();

connection.connect();

// this will be useful so that you can show a typical 0-100% progress bar

int fileLength = connection.getContentLength();

// download the file

InputStream input = new BufferedInputStream(connection.getInputStream());

OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");

byte data[] = new byte[1024];

long total = 0;

int count;

while ((count = input.read(data)) != -1) {

total += count;

// publishing the progress....

Bundle resultData = new Bundle();

resultData.putInt("progress" ,(int) (total * 100 / fileLength));

receiver.send(UPDATE_PROGRESS, resultData);

output.write(data, 0, count);

}

output.flush();

output.close();

input.close();

} catch (IOException e) {

e.printStackTrace();

}

Bundle resultData = new Bundle();

resultData.putInt("progress" ,100);

receiver.send(UPDATE_PROGRESS, resultData);

}

}

注册DownloadService:

activity中这样调用DownloadService// initialize the progress dialog like in the first example

// this is how you fire the downloader

mProgressDialog.show();

Intent intent = new Intent(this, DownloadService.class);

intent.putExtra("url", "url of the file to download");

intent.putExtra("receiver", new DownloadReceiver(new Handler()));

startService(intent);

使用ResultReceiver接收来自DownloadService的下载进度通知private class DownloadReceiver extends ResultReceiver{

public DownloadReceiver(Handler handler) {

super(handler);

}

@Override

protected void onReceiveResult(int resultCode, Bundle resultData) {

super.onReceiveResult(resultCode, resultData);

if (resultCode == DownloadService.UPDATE_PROGRESS) {

int progress = resultData.getInt("progress");

mProgressDialog.setProgress(progress);

if (progress == 100) {

mProgressDialog.dismiss();

}

}

}

}

2.1使用 Groundy library

Groundy 可以帮助你在后台service中运行一些代码,其实也是基于刚刚用到的 ResultReceiver,下面是使用Groundy的大致代码:public class MainActivity extends Activity {

private ProgressDialog mProgressDialog;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();

Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();

Groundy.create(DownloadExample.this, DownloadTask.class)

.receiver(mReceiver)

.params(extras)

.queue();

mProgressDialog = new ProgressDialog(MainActivity.this);

mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

mProgressDialog.setCancelable(false);

mProgressDialog.show();

}

});

}

private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {

@Override

protected void onReceiveResult(int resultCode, Bundle resultData) {

super.onReceiveResult(resultCode, resultData);

switch (resultCode) {

case Groundy.STATUS_PROGRESS:

mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));

break;

case Groundy.STATUS_FINISHED:

Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);

mProgressDialog.dismiss();

break;

case Groundy.STATUS_ERROR:

Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();

mProgressDialog.dismiss();

break;

}

}

};

}

其中GroundyTask的定义如下:public class DownloadTask extends GroundyTask {

public static final String PARAM_URL = "com.groundy.sample.param.url";

@Override

protected boolean doInBackground() {

try {

String url = getParameters().getString(PARAM_URL);

File dest = new File(getContext().getFilesDir(), new File(url).getName());

DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));

return true;

} catch (Exception pokemon) {

return false;

}

}

}

但是请记住要在activity中注册了相关service才行:

三、使用DownloadManager

其实这才是解决下载问题的终极方法,因为他使用起来实在是太简单了。可惜只有在GingerBread 之后才能使用。

先判断能不能使用DownloadManager:/**

* @param context used to check the device version and DownloadManager information

* @return true if the download manager is available

*/

public static boolean isDownloadManagerAvailable(Context context) {

try {

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {

return false;

}

Intent intent = new Intent(Intent.ACTION_MAIN);

intent.addCategory(Intent.CATEGORY_LAUNCHER);

intent.setClassName("com.android.providers.downloads.ui", "com.android.providers.downloads.ui.DownloadList");

List list = context.getPackageManager().queryIntentActivities(intent,

PackageManager.MATCH_DEFAULT_ONLY);

return list.size() > 0;

} catch (Exception e) {

return false;

}

}

如果能,那么只需要这样就可以开始下载一个文件了:String url = "url you want to download";

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

request.setDescription("Some descrition");

request.setTitle("Some title");

// in order for this if to run, you must use the android 3.2 to compile your app

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

request.allowScanningByMediaScanner();

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

}

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");

// get download service and enqueue file

DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

manager.enqueue(request);

下载的进度会在消息通知中显示。

总结

前两种方法需要你考虑的东西很多,除非是你想完全控制下载的整个过程,否则用最后一种比较省事。

android后台文件下载库,android中如何下载文件并显示下载进度相关推荐

  1. python实现http下载文件-Python HTTP下载文件并显示下载进度条功能的实现

    下面的Python脚本中利用request下载文件并写入到文件系统,利用progressbar模块显示下载进度条. 其中利用request模块下载文件可以直接下载,不需要使用open方法,例如: im ...

  2. Android中如何下载文件并显示下载进度

    原文地址:http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1125/2057.html 这里主要讨论三种方式:AsyncTask.Serv ...

  3. python如何实现下载文件_python实现下载文件的三种方法

    python实现下载文件的三种方法 Python开发中时长遇到要下载文件的情况,最常用的方法就是通过Http利用urllib或者urllib2模块. 当然你也可以利用ftplib从ftp站点下载文件. ...

  4. android下载通知栏,Android开发中实现下载文件通知栏显示进度条

    android开发中实现下载文件通知栏显示进度条. 1.使用asynctask异步任务实现,调用publishprogress()方法刷新进度来实现(已优化) public class myasync ...

  5. android读取工程目录下的文件,Android编程实现读取工程中的txt文件功能

    本文实例讲述了Android编程实现读取工程中的txt文件功能.分享给大家供大家参考,具体如下: 1. 众所周知,Android的res文件夹是用来存储资源的,可以在res文件夹下建立一个raw文件夹 ...

  6. Android 下载文件并显示进度条

    2019独角兽企业重金招聘Python工程师标准>>> OK,上一篇文章讲了上传文件到服务端,并显示进度条 那么这边文章主要讲下载文件并显示进度条. 由于简单,所以只上传代码.还是需 ...

  7. 【踩坑】Linux java中ftp下载文件,解压文件损坏,以及图片下载打开只显示下载路径的问题

    [踩坑]Linux java中ftp下载文件,解压文件损坏,以及图片下载打开只显示下载路径的问题 一. 问题重现 二. 问题解决思路 1. 确认是不是上传就导致数据出错了 2. 是不是平台问题 三. ...

  8. ASP.NET中常用的文件上传下载方法

    ASP.NET中常用的文件上传下载方法 文件的上传下载是我们在实际项目开发过程中经常需要用到的技术,这里给出几种常见的方法,本文主要内容包括: 1.如何解决文件上传大小的限制 2.以文件形式保存到服务 ...

  9. 实现在 .net 中使用 HttpClient 下载文件时显示进度

    在 .net framework 中,要实现下载文件并显示进度的话,最简单的做法是使用 WebClient 类.订阅 DownloadProgressChanged 事件就行了. 但是很可惜,WebC ...

最新文章

  1. php 二维数组排序,多维数组排序
  2. sqli-labs(10)
  3. Stanford UFLDL教程 稀疏自编码器符号一览表
  4. [转]自动驾驶基础--路径规划
  5. springboot整合flink
  6. 机器学习图像源代码_使用带有代码的机器学习进行快速房地产图像分类
  7. ios 下拉放大 上拉缩小_为啥鞠婧祎发量这么多?截图放大十倍她的“发缝”,网友:真密集...
  8. 深入理解RocketMQ中的NameServer
  9. Win11 不支持移动任务栏位置;苹果将推出更大尺寸的 iPad Pro;iOS 15 更新 Beta2 版本|极客头条...
  10. 用递归将嵌套的JSON对象遍历出来,转为二维数组 或一维数组
  11. 计算机c语言报告册,计算机c语言实验报告.docx
  12. 保山一中2021高考成绩查询,云南省保山第一中学
  13. 2030年中国GDP将超越美国成为世界第一?
  14. SQL查询实现差集(补集)运算
  15. css media怎么用,css中@media属性如何使用
  16. ffmpeg java 实时视频流转码
  17. 【神经网络参数初始化方法】
  18. 找最大ASCII字符
  19. linux学生入门,Linux入门之《Linux从入门到精通》
  20. 创业公司股权分配的七大实操建议

热门文章

  1. 一起来学Spring Cloud | 第五章:熔断器 ( Hystrix)
  2. 复用io selectors模块
  3. 微信小程序函数调用监控
  4. Codeforces 448C Painting Fence:分治
  5. net user命令详解
  6. C++文本处理_文件读写
  7. Linux编辑器vi使用方法详细介绍
  8. WINCE的内存配置
  9. 新思科技助力IBM将AI计算性能提升1000倍
  10. OpenCV计算机视觉编程攻略之行人检测