码迷,mamicode.com
首页 > 编程语言 > 详细

多线程下载服务端图片资源

时间:2015-08-02 16:52:53      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

服务端情况是:http://192.168.1.105:8080:/web/sky.jpg 敲回车,就在浏览器展现图片资源>>>>>>> 服务端代码省略。。。。

down_activity.xml(button是提交网络请求下载图片的,textview是一旦下载完毕进行界面提示的)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载" />

</LinearLayout>

DownLoadActivity

package com.lw.http01;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class DownLoadActivity extends Activity {
	private TextView textView;
	private Button button;
	private int count = 0;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			int result = msg.what;
			count += result;
			if (count == 3) {
				// 下载完毕更新ui界面即可
				textView.setText("download success");

			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.down_activity);
		textView = (TextView) findViewById(R.id.textView);
		button = (Button) findViewById(R.id.button);

		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				/**
				 * 在子线程中获取网络图片
				 */
				new Thread() {
					public void run() {
						DownLoad load = new DownLoad(handler);
						load.downLoadFile("http://192.168.1.105:8080:/web/sky.jpg");
					};

				}.start();
			}
		});

	}

}

DownLoad

package com.lw.http01;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

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

public class DownLoad {
	/**
	 * 创建3个线程的线程池
	 */
	private Executor threadPool = Executors.newFixedThreadPool(3);

	static class DownLoadRunnable implements Runnable {
		/**
		 * 定义传递过来的参数
		 */
		private String url;
		private String fileName;
		private long start;
		private long end;
		private Handler handler;

		public DownLoadRunnable(String url, String fileName, long start,
				long end, Handler handler) {
			super();
			this.url = url;
			this.fileName = fileName;
			this.start = start;
			this.end = end;
			this.handler = handler;
		}

		@Override
		public void run() {
			try {
				// 创建url地址,并且设置参数值
				URL httpUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) httpUrl
						.openConnection();
				conn.setReadTimeout(5000);
				conn.setRequestMethod("GET");
				// http协议,请求指定长度的流信息
				conn.setRequestProperty("Range", "bytes=" + start + "-" + end);

				// 定位写入信息到指定文件目录中
				RandomAccessFile access = new RandomAccessFile(new File(
						fileName), "rwd");
				// 去捕捉起始点--将文件记录指针定位到pos位置。
				access.seek(start);
				// 获取输入路,从服务器得到文件
				InputStream in = conn.getInputStream();
				byte[] b = new byte[1024 * 4];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					// 输出
					access.write(b, 0, len);
				}
				if (access != null) {
					access.close();

				}
				if (in != null) {
					in.close();

				}
				// 每个线程下载完毕后,发送消息
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			} catch (Exception e) {

			}
		}
	}

	/**
	 * 定义handler是因为 在DownLoadRunnable中需要有handler发送消息(每个线程下载完毕发送消息,更新主界面)
	 */
	private Handler handler;

	public DownLoad(Handler handler) {
		this.handler = handler;
	}

	public void downLoadFile(String url) {
		try {
			/**
			 * 创建url地址信息,并且设置参数
			 */
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl
					.openConnection();
			conn.setReadTimeout(5000);
			conn.setRequestMethod("GET");

			// 拿到网络资源的总体大小
			int count = conn.getContentLength();
			// 每个下载下载的大小
			int block = count / 3;
			// 获取网路资源的后缀名
			String fileName = getFile(url);
			// 得到文件夹的根目录
			File parent = Environment.getExternalStorageDirectory();
			// 获取文件的真实绝对路径
			File downLoadFile = new File(parent, fileName);
			/**
			 * 11总体大小/3 blcok为3 余2 第一个线程 0-2 第二个线程 3-5 第三个线程 6-10
			 */
			for (int i = 0; i < 3; i++) {
				long start = i * block;
				long end = (i + 1) * block - 1;
				if (i == 2) {
					end = count;
				}
				/**
				 * 传递start、end是因为setRequestProperty因为协议需要这2个参数
				 * url是因为每个线程下载需要url地址信息 hander是发送消息,更新ui界面
				 */
				DownLoadRunnable runnable = new DownLoadRunnable(url,
						downLoadFile.getAbsolutePath(), start, end, handler);
				threadPool.execute(runnable);
			}
		} catch (Exception e) {

		}
	}

	// 通过url拿到文件的后缀名字
	public String getFile(String url) {
		return url.substring(url.lastIndexOf("/") + 1);
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

多线程下载服务端图片资源

标签:

原文地址:http://blog.csdn.net/u013210620/article/details/47207879

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!