




下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Androidsdk3.0 编译通过packagecom.download;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;.URL;.URLConnection;importorg.apache.http.client.ClientProtocolException;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Environment;importa
2、ndroid.os.Handler;importandroid.os.Message;importandroid.util.Log;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.ProgressBar;importandroid.widget.TextView;importandroid.widget.Toast;publicclassAndroidDownLoadActivityextendsActivitypri
3、vateButtonDownloadTextButton=null;privateButtonDownloadMp3Button=null;ProgressBarpb;TextViewtv;intfileSize;intdownLoadFileSize;StringfileEx,fileNa,filename;privateHandlerhandler=newHandler()OverridepublicvoidhandleMessage(Messagemsg)/定义一个 Handler,用于处理下载线程与if(!Thread.currentThread().isInterrupted()sw
4、itch(msg.what)case0:pb.setMax(fileSize);UI 间通讯case 1:pb.setProgress(downLoadFileSize);intresult=downLoadFileSize*100/fileSize;tv.setText(result+%);break;case 2:Toast.makeText(AndroidDownLoadActivity.this,文件下载完成,1).show();break;case-1:Stringerror=msg.getData().getString(error);Toast.makeText(AndroidD
5、ownLoadActivity.this,error,1).show();break;super.handleMessage(msg);/*downloadfiletosdcard.*/publicvoiddown_file(Stringurl,Stringpath)throwsIOException/下载函数filename=url.substring(url.lastIndexOf(/)+1);/获取文件名URLmyURL=newURL(url);URLConnectionconn=myURL.openConnection();conn.connect();InputStreamis=co
6、nn.getInputStream();this.fileSize=conn.getContentLength();/根据响应获取文件大小Log.i(value,length=+this.fileSize);if(this.fileSize=0)thrownewRuntimeException(无法获知文件大小);if(is=null)thrownewRuntimeException(streamisnull);Filefile=newFile(Environment.getExternalStorageDirectory(),filename);FileOutputStreamfos=new
7、FileOutputStream(file);/把数据存入路径+文件名bytebuf 口=newbyte1024;downLoadFileSize=0;sendMsg(0);do/循环读取intnumread=is.read(buf);if(numread=-1)break;)fos.write(buf,0,numread);downLoadFileSize+=numread;sendMsg(1);/更新进度条while(true);sendMsg(2);/通知下载完成tryis.close();catch(Exceptionex)Log.e(tag,error:+ex.getMessage(
8、),ex);privatevoidsendMsg(intflag)Messagemsg=newMessage();msg.what=flag;handler.sendMessage(msg);/*Calledwhentheactivityisfirstcreated.*/OverridepublicvoidonCreate(BundlesavedInstanceState)(super.onCreate(savedlnstanceState);setContentView(R.layout.main);super.onCreate(savedInstanceState);setContentV
9、iew(R.layout.main);pb=(ProgressBar)findViewById(R.id.down_pb);tv=(TextView)findViewById(R.id.tv);newThread()(publicvoidrun()(try(down_file(http:/下载路径,/sdcard/);/下载文件,参数:第一个 URL.,第二个存放路径catch(ClientProtocolExceptione)(/TODOAuto-generatedcatchblocke.printStackTrace();catch(IOExceptione)(/TODOAuto-gene
10、ratedcatchblocke.printStackTrace();.start();DownloadTextButton=(Button)findViewById(R.id.DownTextButtonId);DownloadTextButton.setOnClickListener(newDownTextButtonListener();DownloadMp3Button=(Button)findViewById(R.id.DownMp3ButtonId);DownloadMp3Button.setOnClickListener(newDownMp3ButtonListener();pr
11、ivateclassDownTextButtonListenerimplementsOnClickListener(publicvoidonClick(Viewv)(Threadthread=newThread(newRunnable()publicvoidrun()(/TODOAuto-generatedmethodstubHttpDownloaderhttpDownloader=newHttpDownloader();Stringirc=httpDownloader.download(http:/下载路径,);System.out.println(irc););thread.start()
12、;privateclassDownMp3ButtonListenerimplementsOnClickListener(publicvoidonClick(Viewv)(Threadthread=newThread(newRunnable()(publicvoidrun()(/TODOAuto-generatedmethodstubHttpDownloaderhttpDownloader=newHttpDownloader();intresult=httpDownloader.downFile(http:/下载路径,test/,love.exe);System.out.println(resu
13、lt););thread.start();packagecom.download;importjava.io.BufferedReader;importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;.HttpURLConnection;.MalformedURLException;.URL;.URLConnection;importandroid.util.Log;publicclassHttpDownloaderprivateURLurl=nul
14、l;publicStringdownload(StringurlStr)StringBuffersb=newStringBuffer();Stringline=null;BufferedReaderbuffer=null;try/创建一个 url 对象 url=newURL(urlStr);/创建一个 Http 连接对象/HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();URLConnectionurlConn=url.openConnection();urlConn.connect();intfileSize=u
15、rlConn.getContentLength();/根据响应获取文件大小Log.d(filesize,*+fileSize);/使用 IO 流读取数据buffer=newBufferedReader(newInputStreamReader(urlConn.getInputStream();while(line=buffer.readLine()!=null)(sb.append(line);catch(Exceptione)(e.printStackTrace();finally(try(buffer.close();catch(Exceptione)(e.printStackTrace(
16、);returnsb.toString();publicintdownFile(StringurlStr,Stringpath,StringfileName)(InputStreaminputStream=null;try(FileUtilsfileUtils=newFileUtils();if(fileUtils.isFileExist(path+fileName)(return1;else(inputStream=getInputStreamFromUrl(urlStr);FileresultFile=fileUtils.write2SDFromInput(path,fileName,in
17、putStream);if(resultFile=null)(return-1;catch(Exceptione)(e.printStackTrace();return-1;finally(try(inputStream.close();catch(Exceptione)(e.printStackTrace();return0;privateInputStreamgetInputStreamFromUrl(StringurlStr)throwsMalformedURLException,IOException(/TODOAuto-generatedmethodstuburl=newURL(ur
18、lStr);HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();InputStreaminputStream=urlConn.getInputStream();returninputStream;packagecom.download;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importandroid.
19、os.Environment;publicclassFileUtils(privateStringSDPATH;publicStringgetSDPATH()(returnSDPATH;)publicFileUtils()(SDPATH=Environment.getExternalStorageDirectory()+/;)publicFilecreateSDFile(Stringfilename)throwsIOException(Filefile=newFile(SDPATH+filename);file.createNewFile();returnfile;)publicFilecreateSDDir(
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025春季中国南水北调集团水网智慧科技有限公司实习生招募6人考前自测高频考点模拟试题及参考答案详解一套
- 2025年福建省泉州市安溪龙门中学招聘1人模拟试卷参考答案详解
- 2025湖南屈原管理区凤凰乡人民政府公益性岗位招聘模拟试卷完整答案详解
- 2025年合肥经济学院人才招聘72人考前自测高频考点模拟试题及一套答案详解
- 2025辽宁葫芦岛籍公费师范生专项招聘4人考前自测高频考点模拟试题附答案详解(考试直接用)
- 2025年赣南医科大学高层次人才招聘180人模拟试卷参考答案详解
- 2025贵州织金翔盛工业发展有限公司面向社会招聘10人模拟试卷附答案详解(模拟题)
- 2025广东省机场管理集团有限公司揭阳潮汕机场公司招聘模拟试卷及一套答案详解
- 2025届中国兵器装备春季校园招聘模拟试卷及一套答案详解
- 2025年烟台市芝罘区卫生类事业单位公开招聘高层次人才(11人)模拟试卷及答案详解(名校卷)
- 工业机器人基础课件:装配机器人及其操作应用
- 激素与肥胖的关系
- 网约车全国公共科目考试题库与答案
- 【《离心泵叶轮的水力设计过程案例综述》2200字】
- 胃手术并发症及处理
- 2025至2030 中国热成型钢(PHS)行业现状调查与前景策略研究报告
- 执法监督培训课件
- 股权投资基金培训课件
- 千川投手培训课件
- 2025年中国注塑机熔胶筒螺杆市场调查研究报告
- 职业培训班级管理制度
评论
0/150
提交评论