现在的位置: 首页 > 综合 > 正文

android 多线程并发下载文件

2017年12月25日 ⁄ 综合 ⁄ 共 7965字 ⁄ 字号 评论关闭

Download.java

package com.wansha;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

import com.wansha.download.util.DownloadUtil;

public class Download extends Activity {
	private ProgressBar bar1;
	private Button downFile;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.bar1 = (ProgressBar)this.findViewById(R.id.bar1);
        this.downFile = (Button)this.findViewById(R.id.downfile);
        this.downFile.setOnClickListener(new downFileListener());
        
    }
    class downFileListener implements OnClickListener{
    	public void onClick(View arg0) {
    		bar1.setVisibility(View.VISIBLE);
    		DownloadUtil downloadutil = new DownloadUtil();
    		downloadutil.Save2SDCard("http://192.168.0.137:8080/navigater/admin/SSHDemo.zip", "peng/", "sharp.zip");
    		
    	}
    }
    Handler handler = new Handler(){
    	public void handleMessage(Message msg) {
    		Log.d("mydebug", "hehh!" + msg.arg1);
    		bar1.setProgress(msg.arg1);
    		if(msg.arg1==100){
    			bar1.setVisibility(View.GONE);
    		}
    	};
    };
}

DownloadFile.java

package com.wansha.download.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class DownloadFile {
	private File file;
	private String url;
	private String fileName;
	private int startPos;
	private int endPos;
	private long totalSize;
	private int threadNumTotal =1;
	private int currentThread =1;
	private static int BUFFER_SIZE = 1024*80;
	
	public int getBUFFER_SIZE() {
		return BUFFER_SIZE;
	}
	public int getThreadNumTotal() {
		return threadNumTotal;
	}
	public void setThreadNumTotal(int threadNumTotal) {
		this.threadNumTotal = threadNumTotal;
	}
	public int getCurrentThread() {
		return currentThread;
	}
	public void setCurrentThread(int currentThread) {
		this.currentThread = currentThread;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public int getStartPos() {
		return startPos;
	}
	public void setStartPos(int startPos) {
		this.startPos = startPos;
	}
	public int getEndPos() {
		return endPos;
	}
	public void setEndPos(int endPos) {
		this.endPos = endPos;
	}
	public long getTotalSize() {
		return totalSize;
	}
	public void setTotalSize(long totalSize) {
		this.totalSize = totalSize;
	}
	
	public long getURLTotalSize() {
		try{
			URL url = new URL(this.url);
			HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
			httpConn.setRequestMethod("GET");                         //以GET方式连接  
			if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
				return httpConn.getContentLength();
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return 0;
		}
		return 0;
	}
	
	public InputStream getInputStreamByThreadNum(){
		InputStream is = null;
		try{
			if(this.url != null && !"".equals(this.url)){
				long urlTotalSize = getURLTotalSize();
				Log.d("mydebug", "threadNumTotal         " + this.threadNumTotal);
				long spanSize = (long)Math.ceil((float)urlTotalSize/this.threadNumTotal);
				Log.d("mydebug", "spanSize         " + spanSize);
				this.setStartPos((int)((this.currentThread-1)*spanSize));
				int ends = (int)(this.currentThread*spanSize-1);
				if(ends > urlTotalSize){
					this.setEndPos((int)urlTotalSize-1);
				}else{
					this.setEndPos(ends);
				}
				
				URL url = new URL(this.url);
				HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
	            httpConn.setRequestMethod("GET");                         //以GET方式连接  
				httpConn.setRequestProperty("Connection", "Keep-Alive");  //保持一直连接  
                httpConn.setConnectTimeout(60 * 1000 * 5);                //连接超时5分钟  
                httpConn.setAllowUserInteraction(true);  
                httpConn.setRequestProperty("Range", "bytes=" + getStartPos() + "-" + getEndPos());
                Log.d("mydebug", "         " + getStartPos() + "            " + getEndPos());
                is = new BufferedInputStream(httpConn.getInputStream(),DownloadFile.BUFFER_SIZE);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return is;
	}
	
	public InputStream getInputStreamByPos(){
		try{
			if(this.url != null && !"".equals(this.url)){
				if(this.startPos != 0 || this.endPos != 0){
					URL url = new URL(this.url);
					HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
		            httpConn.setRequestMethod("GET");                         //以GET方式连接  
					httpConn.setRequestProperty("Connection", "Keep-Alive");  //保持一直连接  
	                httpConn.setConnectTimeout(60 * 1000 * 5);                //连接超时5分钟  
	                httpConn.setAllowUserInteraction(true);  
	                httpConn.setRequestProperty("Range", "bytes=" + getStartPos() + "-" + getEndPos());  
					Log.d("mydebug", "readding....6           " + httpConn.getResponseCode());
//					if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
						Log.d("mydebug", "readding....8           " + this.startPos + "````````````````````````" + this.endPos);
							Log.d("mydebug", "hello world");
//			                httpConn.setRequestProperty("Range", "bytes=" + getStartPos() + "-" + getEndPos());  
			                Log.d("mydebug", "start ------>" + this.startPos + "  endPos" + this.endPos);
			                Log.d("mydebug", "readding....7");
							return new BufferedInputStream(httpConn.getInputStream(),DownloadFile.BUFFER_SIZE);
	
//					}
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
		return null;
	}
	public static void main(String[] args) throws Exception {
		DownloadFile downloadFile = new DownloadFile();
		downloadFile.setUrl("http://www.baidu.com/index.html");
		downloadFile.getInputStreamByPos();
	}
}

DownloadUtil.java

package com.wansha.download.util;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class DownloadUtil {
	private static int threadNum = 10;
	private int sign = 0;
	public static int getThreadNum() {
		return threadNum;
	}

	public static void setThreadNum(int threadNum) {
		DownloadUtil.threadNum = threadNum;
	}

	public DownloadUtil(){
		
	}

	private final static String SDPATH = Environment.getExternalStorageDirectory().getPath() + "/";
	
	public boolean isExistFile(String filePath){
		File file = new File(filePath);
		return file.exists();
	}
	
	public void createDir(String dirPath){
		if(dirPath != null || !"".equals(dirPath)){
			File file = new File(dirPath);
			if(!file.isDirectory()){
				file.mkdirs();
			}
		}
	}
	
	public int Save2SDCard(String urlAddress, String saveDir, String fileName){
		createDir(DownloadUtil.SDPATH + saveDir);
		try{
		File file = new File(DownloadUtil.SDPATH + saveDir, fileName);
		Log.d("mydebug", "fileName....1" + DownloadUtil.SDPATH + saveDir + fileName);
		if(file.exists())file.delete();
		ExecutorService service = Executors.newFixedThreadPool(10);
		CountDownLatch countDownLatch = new CountDownLatch(DownloadUtil.threadNum);
		Log.d("mydebug", "readding....1");
		for(int i=1; i<=DownloadUtil.threadNum; i++){
			Log.d("mydebug", "readding....2");
			DownloadFile downloadFile = new DownloadFile();
				downloadFile.setUrl(urlAddress);
				downloadFile.setThreadNumTotal(DownloadUtil.threadNum);
				downloadFile.setCurrentThread(i);
			RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");
			
			
//			boolean flag = this.handler.post(new SaveFileThread(countDownLatch, this.handler));
			service.execute(new SaveFileThread(randomAccessFile, downloadFile, countDownLatch));
		}
		countDownLatch.await();
		service.shutdown();
		Log.d("mydebug", "download is finish!");
		return 0;
		}catch(Exception ex){
			ex.printStackTrace();
			return -1;
		}
	}
	
	class MyRunnable implements Runnable{
    	private Handler handler;
    	public MyRunnable(){
    		 
    	}
    	public MyRunnable(Handler handler){
    		this.handler = handler;
    	}
    	public void run() {
	    		sign += 10;
	    		Message message = this.handler.obtainMessage();
	    		message.arg1 = sign;
	    		try{
	    			Thread.sleep(2000);
	    		}catch(Exception ex){
	    			ex.printStackTrace();
	    		}
	    		this.handler.sendMessage(message);
    	};

    };
	
	class SaveFileThread implements Runnable{
		private RandomAccessFile randomFile;
		private DownloadFile downloadFile;
		private CountDownLatch countDownLatch;
		public SaveFileThread() {
		}

		public SaveFileThread(RandomAccessFile randomFile, DownloadFile downloadFile, CountDownLatch countDownLatch) {
			this.randomFile = randomFile;
			this.downloadFile = downloadFile;
			this.countDownLatch = countDownLatch;
		}


		public void run() {
			try{
				InputStream is = this.downloadFile.getInputStreamByThreadNum();
				this.randomFile.seek(this.downloadFile.getStartPos());
				
				byte[] by = new byte[1024*80];
				int length = 0;
				
				while(-1 != (length = is.read(by))){
					this.randomFile.write(by, 0, length);
				}
				
				is.close();
				this.randomFile.close();
				this.countDownLatch.countDown();
				
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}
}

抱歉!评论已关闭.