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

Androidx学习笔记(46)--- 用进度条显示下载进度

2016-02-03 22:17 525 查看

用进度条显示下载进度

拿到下载文件总长度时,设置进度条的最大值
//设置进度条的最大值
pb.setMax(length);
进度条需要显示三条线程的整体下载进度,所以三条线程每下载一次,就要把新下载的长度加入进度条定义一个int全局变量,记录三条线程的总下载长度
int progress;
刷新进度条
while((len = is.read(b)) != -1){
raf.write(b, 0, len);

//把当前线程本次下载的长度加到进度条里
progress += len;
pb.setProgress(progress);
每次断点下载时,从新的开始位置开始下载,进度条也要从新的位置开始显示,在读取缓存文件获取新的下载开始位置时,也要处理进度条进度
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
int newStartIndex = Integer.parseInt(text);

//新开始位置减去原本的开始位置,得到已经下载的数据长度
int alreadyDownload = newStartIndex - startIndex;
//把已经下载的长度设置入进度条
progress += alreadyDownload;

添加文本框显示百分比进度

tv.setText(progress * 100 / pb.getMax() + "%");


测试代码

/**
* 注意:没有判断SD卡是否存在,剩余空间
*/
public class MainActivity extends ActionBarActivity {
private static int ThreadCount = 3; // 下载线程的数量
private static int finishedThread = 0; // 记录关闭线程的数量 用于删除临时文件
// 确定下载地址
private String path = "http://192.168.1.101:8080/a/b.exe";private String fileName = null;
private String fileType = null ;
private ProgressBar pb = null;
private int currProgressLen = 0;
private TextView tv = null;Handler handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
//把变量改成long,在long下运算
tv.setText((long)pb.getProgress() * 100 / pb.getMax() + "%");
};};@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//获取文件名和后缀名
File file = new File(path);
fileName = file.getName();
fileType = fileName.substring(fileName.lastIndexOf(".") ,fileName.length());
//String fileType = fileName.substring(fileName.lastIndexOf(".") +1,fileName.length());pb = (ProgressBar) findViewById(R.id.progressBar1);tv = (TextView) findViewById(R.id.textView1);}public void click(View v)
{
Thread thread = new Thread()
{
public void run()
{
// 发送get请求,请求这个地址的资源
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
// 拿到所请求资源文件的长度
int length = conn.getContentLength();
// 设置进度条的最大值是原文件的总长度
pb.setMax(length);File file = new File(Environment.getExternalStorageDirectory(), fileName);
// 生成临时文件
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
// 设置临时文件的大小
raf.setLength(length);
raf.close();// 计算出每个线程应该下载多少字节
int size = length / ThreadCount;
for (int i = 0; i < ThreadCount; i++) {
// 计算线程下载的开始位置和结束位置
int startIndex = i * size;
int endIndex = (i + 1) * size - 1;
// 如果是最后一个线程,那么结束位置写死
if (i == ThreadCount - 1) {
endIndex = length - 1;
}
// System.out.println("线程" + i + "的下载区间是:" + startIndex +
// "---" + endIndex);
new DownLoadThread(startIndex, endIndex, i).start();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}};
};thread.start();
}class DownLoadThread extends Thread {
int startIndex;
int endIndex;
int threadId;
public DownLoadThread(int startIndex, int endIndex, int threadId) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
// 再次发送http请求,下载原文件
try {
// 生成一个专门用来记录下载进度的临时文件
File progressFile = new File(Environment.getExternalStorageDirectory(),threadId + ".txt");
// 判断进度临时文件是否存在
if (progressFile.exists()) {
FileInputStream fis = new FileInputStream(progressFile);
BufferedReader br = new BufferedReader(new InputStreamReader(
fis));
// 从进度临时文件中读取出上一次下载的总进度,然后与原本的开始位置相加,得到新的开始位置
int lastIndex = Integer.parseInt(br.readLine());
startIndex += lastIndex;//设置暂停后继续的 当前进度
currProgressLen += lastIndex;
pb.setProgress(currProgressLen);//发送消息,让主线程刷新文本进度
handler.sendEmptyMessage(1);fis.close();
}
HttpURLConnection conn;
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 设置本次http请求所请求的数据的区间
conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
+ endIndex);
// 请求部分数据,相应码是206
if (conn.getResponseCode() == 206) {
// 流里此时只有1/3原文件的数据
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
int total = 0;
// 拿到临时文件的输出流
File file = new File(Environment.getExternalStorageDirectory(), fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
// 把文件的写入位置移动至startIndex
raf.seek(startIndex);
while ((len = is.read(b)) != -1) {
// 每次读取流里数据之后,同步把数据写入临时文件
raf.write(b, 0, len);
total += len;
//System.out.println("线程" + threadId + "下载了" + total);//设置当前进度
currProgressLen += len;
pb.setProgress(currProgressLen);//发送消息,让主线程刷新文本进度
handler.sendEmptyMessage(1);RandomAccessFile progressRaf = new RandomAccessFile(
progressFile, "rwd");
// 每次读取流里数据之后,同步把当前线程下载的总进度写入进度临时文件中
progressRaf.write((total + "").getBytes());
progressRaf.close();
}
System.out
.println("线程" + threadId + "下载完毕-------------------!");
raf.close();
// 线程下载完成自加
MainActivity.finishedThread++;
// 在同步语句块中 删除所有的临时文件
synchronized ( path) {
if (MainActivity.finishedThread == MainActivity.ThreadCount) {
for (int i = 0; i < MainActivity.ThreadCount; i++) {
File f = new File(Environment.getExternalStorageDirectory(),i + ".txt");
f.delete();
}
// 线程下载数量重置
MainActivity.finishedThread = 0;
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: