在模拟器上运行错误
package com.imooc.yongzhao.handlerproject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
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;
/**
* Created by yongzhao on 11/6/18.
*/
public class DownloadActivity extends Activity {
Handler mhandler;
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
/**
* 主线程:
* 1. 点击按键
* 2. 发现下载
* 3. 开启子线程做下载
* 4. 下载完成后通知主线程
* 5. 主线程跟新进度条
*/
final ProgressBar progressBar=(ProgressBar) findViewById(R.id.progressBar1);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
download("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk");
}
}).start();
}
});
mhandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1000001:
progressBar.setProgress((Integer) msg.obj);
break;
case 1000002:
break;
}
}
};
}
private void download(String appurl) {
try {
URL url=new URL(appurl);
try {
URLConnection urlconnection =url.openConnection();
InputStream inputStream=urlconnection.getInputStream();
//获取文件的长度
int contentLength=urlconnection.getContentLength();
//下载
String downloadFileName= Environment.getExternalStorageDirectory()
+ File.separator+"yong"+File.separator;
File file=new File(downloadFileName);
if(!file.exists()){
file.mkdir();
}
String fileName=downloadFileName+"yong.apk";
File apkFile=new File(fileName);
if(apkFile.exists()){
apkFile.delete();
}
int downloadSize=0;
byte[] bytes=new byte[1024];
int length=0;
//下载到fileName文件中
OutputStream outputStream=new FileOutputStream(fileName);
while((length=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,length);
downloadSize+=length;
//更新主界面UI
Message message=Message.obtain();//创建message对象
message.obj=downloadSize*100/contentLength;
message.what=1000001;
mhandler.sendMessage(message);
}
inputStream.close();
outputStream.close();
} catch (IOException e) {
Message message=Message.obtain();//创建message对象
message.what=1000002;
mhandler.sendMessage(message);
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
正在回答 回答被采纳积分+1
- 参与学习 504 人
- 提交作业 1003 份
- 解答问题 1044 个
本专题是专为有Java语言基础想入坑Android开发的同学们准备的。从AndroidUI基础一直到网络,数据存储,一步到位入门Android开发。如果你会Java,那就不要犹豫了~ ~
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星