ProgressBar(下载网络图片进度显示!)

效果图:
[img]
ProgressBar(下载网络图片进度显示!)
[/img]

MainActivity代码如下:
package com.pocketdigi.download;

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

import org.apache.http.client.ClientProtocolException;
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;
/**
 * 根据url获取图片,并存入sdcard
 * 主要是练习ProgressBar进度条的使用。
 * @author zzl
 *
 */
public class MainActivity extends Activity {
	ProgressBar pb;
	TextView tv;
	int fileSize;
	int downLoadFileSize;
	String filename;
	private Button btn_down;
	// 定义一个Handler,用于处理下载线程与UI间通讯
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case 0:
					pb.setMax(fileSize);
				case 1:
					pb.setProgress(downLoadFileSize);
					int result = downLoadFileSize * 100 / fileSize;
					tv.setText(result + "%");
					break;
				case 2:
					Toast.makeText(MainActivity.this, "文件下载完成", 1).show();
					break;
				case -1:
					String error = msg.getData().getString("error");
					Toast.makeText(MainActivity.this, error, 1).show();
					break;
				}
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		pb = (ProgressBar) findViewById(R.id.down_pb);
		tv = (TextView) findViewById(R.id.tv);
		btn_down = (Button) findViewById(R.id.btn_download);
		btn_down.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread() {
					public void run() {
						try {
							down_file(
									"http://wallpaper.pocketdigi.com/upload/1/bigImage/1284565196.jpg",
									"/sdcard/");
							// 下载文件,参数:第一个URL,第二个存放路径
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}.start();
			}
		});

	}

	public void down_file(String url, String path) throws IOException {
		// 下载函数
		filename = url.substring(url.lastIndexOf("/") + 1);
		System.out.println(filename);
		// 获取文件名
		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);
	}

}


main.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView
		android:id="@+id/tv"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="" />
	<ProgressBar
		android:id="@+id/down_pb"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:max="100"
		style="?android:attr/progressBarStyleHorizontal" />
	<Button
		android:text="下载图片"
		android:id="@+id/btn_download"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content" />
</LinearLayout>


AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pocketdigi.download"
      android:versionCode="10"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
   	<!--不要忘记设置网络访问权限-->
	<uses-permission android:name="android.permission.INTERNET"/>
</manifest> 

你可能感兴趣的:(ProgressBar)