public class DownloadActivity extends AppCompatActivity { private Handler handler; ProgressBar progressBar= (ProgressBar) findViewById(R.id.progressBar); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); /* 异步下载文件更新进度条的步骤 主线程 点击按键 发起下载 开启子线程下载 下载完成后通知主线程 主线程更新进度条 */ findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //建立子线程 new Thread(new Runnable() { @Override public void run() { download("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk"); } }).start(); } }); handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 10001: progressBar.setProgress((Integer)msg.obj); break; case 10002: } } }; } private void download(String appUrl) { try { URL url=new URL(appUrl); URLConnection urlconnection=url.openConnection(); InputStream inputStream=urlconnection.getInputStream(); //获取文件的总长度 int contentLength=urlconnection.getContentLength(); /* Environment.getExternalStorageState()获取扩展存储设备的文件目录 然后创建文件名 */ String downloadFolderName= Environment.getExternalStorageState() + 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(); } if(file!=null){ Log.i("TAG","文件简历成功"); } int downloanSize=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); downloanSize+=length; Message message=Message.obtain(); message.obj=downloanSize*100/contentLength; message.what=10001; handler.sendMessage(message); } //关闭数据 inputStream.close(); outputStream.close(); } catch (MalformedURLException e) { Message message2=Message.obtain(); message2.what=10002; handler.sendMessage(message2); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
异步下载文件更新进度条的步骤
最新推荐文章于 2023-05-10 18:12:07 发布