本文主要实现的是Handler通信下载文件并更新进度条。
主要思路:
主线程——点击按钮——发起下载——开启子线程做下载——下载过程中通知主线程——主线程更新进度条
该说不说,上代码!
activity_download代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2"/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:max="100"
android:layout_gravity="center_horizontal"/>
主线程写download,并创建方法:
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
download(APP_URL);
}
}).start();
}
});
子线程下载程序如下:
private void download(String appUrl) {
try {
URL url = new URL(appUrl);//创建对象
URLConnection urlConnection= url.openConnection();//打开连接
InputStream inputStream=urlConnection.getInputStream();//获取数据流
int contentLength=urlConnection.getContentLength();//获取文件总长度
String downloadFolderName= Environment.getExternalStorageDirectory()
+ File.separator+"imooc"+File.separator;//开始下载folder,然后放在SDK目录下面的imooc目录下
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){
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);//handler用来发送信息
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
使用handler传递信息:
mHandler.sendMessage(message);//handler用来发送信息
创建handler:
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case DOWNLOAD_MESSAGE_CODE:
progressBar.setProgress((Integer) msg.obj);
break;
}
}
};
收到相应后,进度条开始更新!
完整的代码如下:
package com.example.handlerproject;
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 androidx.annotation.Nullable;
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 {
public static final int DOWNLOAD_MESSAGE_CODE = 100001;
private static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002;
public static final String APP_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
private Handler mHandler;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
/*
主线程——
点击按钮——
发起下载——
开启子线程做下载——
下载过程中通知主线程——
主线程更新进度条
*/
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
download(APP_URL);
}
}).start();
}
});
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case DOWNLOAD_MESSAGE_CODE:
progressBar.setProgress((Integer) msg.obj);
break;
}
}
};
}
private void download(String appUrl) {
try {
URL url = new URL(appUrl);//创建对象
URLConnection urlConnection= url.openConnection();//打开连接
InputStream inputStream=urlConnection.getInputStream();//获取数据流
int contentLength=urlConnection.getContentLength();//获取文件总长度
String downloadFolderName= Environment.getExternalStorageDirectory()
+ File.separator+"imooc"+File.separator;//开始下载folder,然后放在SDK目录下面的imooc目录下
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){
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);//handler用来发送信息
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}