下你所需,载你所想!
IT技术源码资料下载网站

Handler异步下载文件更新进度条

:其他软件 2020-09-09 16:30:29

Handler异步下载文件更新进度条

异步下载文件的代码如下
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class DownloadActivity extends Activity {
private Handler mHandler;
public static final int DOWNLOAD_MESSAGE_CODE = 100001;
public static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
final ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar);
/**
* 主线程 -->start
* 点击按钮 |
* 发起下载 |
* 开启子线程做下载 |
* 下载完成后通知主线程 | -->主线程更新进度条
*/
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
//这个地方调用下边的download方法
download("…………………………");
}
}).start();
}
});
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case DOWNLOAD_MESSAGE_CODE:
if(msg.obj!=null)
progressBar.setProgress((Integer) msg.obj);
break;
case DOWNLOAD_MESSAGE_FAIL_CODE:
}
}
};
}
private void download(String appUrl){
try {
URL url = new URL(appUrl);
URLConnection urlConnection = url.openConnection();
//io来读取文件
InputStream inputStream = urlConnection.getInputStream();
/**
* 获取文件的总长度
*/
int contentLength = urlConnection.getContentLength();
String downloadFolderName = Environment.getExternalStorageDirectory()
+ File.separator+"imooc"+File.separator;
File file = new File(downloadFolderName);
if (!file.exists()){
file.mkdir();
}
String fileName = downloadFolderName + "imooc.apk";
File apkFile = new File(fileName);
if (apkFile.exists()){
apkFile.delete();
}
int downloadSize = 0;
byte[] bytes = new byte[1024];
int length = 0;
OutputStream outputStream = new FileOutputStream(fileName);
while ((length = inputStream.read(bytes)) != -1){

//参数为public void write(byte[] b,int off,int len):写一个字节数组的一部分
outputStream.write(bytes,0,length);
downloadSize += length;
/**
* update UI
*/
Message message = Message.obtain();
message.obj = downloadSize * 100 / contentLength;
message.what = DOWNLOAD_MESSAGE_CODE;
mHandler .sendMessage(message);
}
inputStream.close();
outputStream.close();
}catch (MalformedURLException e){
notifyDownloadFaild();
e.printStackTrace();
}catch (IOException e){
notifyDownloadFaild();
e.printStackTrace();
}
}
private void notifyDownloadFaild(){
Message message = Message.obtain();
message.what = DOWNLOAD_MESSAGE_FAIL_CODE;
mHandler .sendMessage(message);
}
}
文件的读取要用到的知识有io流,以及刚刚学习的Handler的用法。
其中download的代码部分需要好好理解。