用进度条显示从网络上下载文件进度

/*
* 根据上课的案例,利用进度条控件程序进行下载操作....
*/
public class Aty_HttpDownLoad_ProgressBar extends Activity {
private ProgressBar pB;
private TextView tv_progress;

private static final int DOWNLOADING=1;
private static final int DOWNLOAD_SUCCESS=2;

private double totalsize;
private double currentsize;

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:// 还在下载
double progress=currentsize/totalsize*pB.getMax();
pB.setProgress((int)progress);
tv_progress.setText((int)progress+"%");
break;
case 2:// 下载完成
pB.setVisibility(View.GONE);
tv_progress.setText("100%,下载完成");
Toast.makeText(getApplicationContext(), "下载完成",
Toast.LENGTH_SHORT).show();
break;

default:
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http_downaload_progressbar);

initWidgets();
downloadImage();
}

private void initWidgets() {
pB = (ProgressBar) findViewById(R.id.pB);
tv_progress = (TextView) findViewById(R.id.tv_progress);
pB.setMax(100);

}

// 新写一个方法,从网上读取图片数据,显示在界面上
public void downloadImage() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(
"http://10.0.2.2:8080/News/assets/myradio.mp4");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setDefaultUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(5000);
connection.setRequestMethod("POST");

InputStream is = connection.getInputStream();

totalsize=connection.getContentLength();//文件总大小
// 字符读用Bufferedreader,字节用DataInputstream
// 写入内存卡,放在那个位置:放到SD卡上,名字app7.png
File downloadFile = new File(Environment
.getExternalStorageDirectory(), "/myradio.mp4");
DataOutputStream dos = new DataOutputStream(
new FileOutputStream(downloadFile));
int len = 0;
byte[] buffer = new byte[4096];
while ((len = is.read(buffer)) != -1) {
currentsize+=len;//当前读取的文件大小
dos.write(buffer, 0, len);
handler.sendEmptyMessage(DOWNLOADING);
}
handler.sendEmptyMessage(DOWNLOAD_SUCCESS);
dos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}).start();
}
}

原文地址:https://www.cnblogs.com/wangfeng520/p/5066811.html