Android 文件下载

在4.0系统下会遇到很多问题,遇到的问题参考:

Android 4.0文件下载失败

下面是文件下载实现代码:

package com.luchg.health.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

/**
 * 文件下载类
 * @author lc
 *
 */
public class DownloadFile implements Runnable {
	
	private String downloadUrl = null;	//下载url
	private String downloadPath = null;	//下载路径
	private String fileName = null;	//下载文件名称
	private Context context = null;	//context用于显示Toast
	
	public DownloadFile(Context context, String downloadUrl, String downloadPath, String fileName){
		this.context = context;
		this.downloadUrl = downloadUrl;
		this.downloadPath = downloadPath;
		this.fileName = fileName;
	}
	
	@Override
	public void run() {
		try {
			
			//创建连接
			URL url = new URL(downloadUrl);
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestMethod("GET");
			urlConn.connect();
			
			//连接获取inputstream
			InputStream inputStream = urlConn.getInputStream();
			int length = inputStream.available();	//获取长度
			byte[] buffer = new byte[length];	//创建byte数组
			//buffer包装
			BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); 
			FileOutputStream fileOutputStream = new FileOutputStream(downloadPath);
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
			
			int len = bufferedInputStream.read(buffer);
	        while(len != -1){
	        	bufferedOutputStream.write(buffer, 0, len);
	        	len = bufferedInputStream.read(buffer);
	        }
			
	        //关闭所有连接
	        bufferedOutputStream.close();
	        bufferedInputStream.close();
	        fileOutputStream.close();
	        inputStream.close();
	        urlConn.disconnect();
	        
	        //
	        Looper.prepare();
			Log.i("---my tag---", "下载完成:"+downloadPath);
			Toast.makeText(context, fileName+"下载完成...", Toast.LENGTH_LONG).show();
			Looper.loop();
			
		} catch (Exception e) {
			Looper.prepare();
			Toast.makeText(context, fileName+"下载失败,请稍后再试...", Toast.LENGTH_LONG).show();
			Looper.loop();
			e.printStackTrace();
		}
		
	}
}

然后在调用下载时,启动线程:

DownloadFile downloadFile = new DownloadFile(getApplication(),url,downloadPath+id+".zip",title);
				new Thread(downloadFile).start();

 

发表评论