您的位置:首页 > 移动开发 > Android开发

Android 文件下载进度条的实现

2014-08-27 11:13 555 查看
Android 中很多地方都需要用到线程下载。下面我谢了个简单的下载图片的demo。望对你们有到帮助.

首先,配置权限,

在 AndroidManifest.xml里面的application节点下面配置需要用到的权限

<!--访问网络的权限-->
    <uses-permission android:name="android.permission.INTERNET" />
    <!--访问SDcard的权限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


权限添加完成,布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button 
        android:id="@+id/btn_1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="点击下载图片"
        />

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="" />

    <ProgressBar
        android:id="@+id/down_pb"
        style="?android:attr/progressBarStyleHorizontal"
        mce_style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100" />

</LinearLayout>


接来下就是写代码了,代码其实很简单,话不多说,我直接上传:

package com.lh.thread;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

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 android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {
	/** Called when the activity is first created. */
	ProgressBar mPb;
	TextView mTv;
	Button mBtn;
	int fileSize;
	int downLoadFileSize;
	String fileEx, fileNa, filename;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {// 定义一个Handler,用于处理下载线程与UI间通讯
			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case 0:
					mPb.setMax(fileSize);
				case 1:
					mPb.setProgress(downLoadFileSize);
					int result = downLoadFileSize * 100 / fileSize;
					mTv.setText(result + "%");
					break;
				case 2:
					Toast.makeText(Main.this, "文件下载完成", 1).show();
					break;
				case -1:
					String error = msg.getData().getString("error");
					Toast.makeText(Main.this, error, 1).show();
					break;
				}
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//初始化控件
		mPb = (ProgressBar) findViewById(R.id.down_pb);
		mTv = (TextView) findViewById(R.id.tv);
		mBtn=(Button) findViewById(R.id.btn_1);
		mBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//启动线程进行下载
				new Thread() {
					public void run() {
						try {
							down_file(
									"http://att.bbs.duowan.com/forum/201310/23/151916t9kdya2gia0a21la.jpg",
									"/sdcard/");
							// 下载文件,参数:第一个URL,第二个存放路径
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
					}
				}.start();
			}
		});
		
	}

	/**
	 * 此方法描述的是:下载文件并保存   
	 * @param url
	 * @param path
	 * @throws IOException  void
	 */
	public void down_file(String url, String path) throws Exception {
		Log.i("AAAAAA", "~~~~~~~~~存储路径是"+path);
		// 下载函数
		filename = url.substring(url.lastIndexOf("/") + 1);
		// 获取文件名
		URL myURL = new URL(url);
		URLConnection conn = myURL.openConnection();
		conn.connect();
		InputStream is = conn.getInputStream();
		this.fileSize = conn.getContentLength();// 根据响应获取文件大小
		if (this.fileSize <= 0)
			throw new RuntimeException("无法获知文件大小 ");
		if (is == null)
			throw new RuntimeException("stream is null");
		FileOutputStream fos = new FileOutputStream(path + filename);
		// 把数据存入路径+文件名
		byte buf[] = new byte[1024];
		downLoadFileSize = 0;
		sendMsg(0);
		do {
			// 循环读取
			int numread = is.read(buf);
			if (numread == -1) {
				break;
			}
			fos.write(buf, 0, numread);
			downLoadFileSize += numread;
			sendMsg(1);// 更新进度条
		} while (true);
		sendMsg(2);// 通知下载完成
		try {
			is.close();
		} catch (Exception ex) {
			Log.e("tag", "error: " + ex.getMessage(), ex);
		}
	}

	private void sendMsg(int flag) {
		Message msg = new Message();
		msg.what = flag;
		handler.sendMessage(msg);
	}
}
好了,进度条下载就完成了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: