android文件下载及进度条.docx
《android文件下载及进度条.docx》由会员分享,可在线阅读,更多相关《android文件下载及进度条.docx(14页珍藏版)》请在冰豆网上搜索。
android文件下载及进度条
Androidsdk3.0编译通过
packagecom.download;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
import.URL;
import.URLConnection;
importorg.apache.http.client.ClientProtocolException;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.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;
publicclassAndroidDownLoadActivityextendsActivity
{
privateButtonDownloadTextButton=null;
privateButtonDownloadMp3Button=null;
ProgressBarpb;
TextViewtv;
intfileSize;
intdownLoadFileSize;
StringfileEx,fileNa,filename;
privateHandlerhandler=newHandler()
{
@Override
publicvoidhandleMessage(Messagemsg)
{//定义一个Handler,用于处理下载线程与UI间通讯
if(!
Thread.currentThread().isInterrupted())
{
switch(msg.what){
case0:
pb.setMax(fileSize);
case1:
pb.setProgress(downLoadFileSize);
intresult=downLoadFileSize*100/fileSize;
tv.setText(result+"%");
break;
case2:
Toast.makeText(AndroidDownLoadActivity.this,"文件下载完成",1)
.show();
break;
case-1:
Stringerror=msg.getData().getString("error");
Toast.makeText(AndroidDownLoadActivity.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=conn.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=newFileOutputStream(file);
//把数据存入路径+文件名
bytebuf[]=newbyte[1024];
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);//通知下载完成
try
{
is.close();
}catch(Exceptionex)
{
Log.e("tag","error:
"+ex.getMessage(),ex);
}
}
privatevoidsendMsg(intflag)
{
Messagemsg=newMessage();
msg.what=flag;
handler.sendMessage(msg);
}
/**Calledwhentheactivityisfirstcreated.*/
@Override
publicvoidonCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(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-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}.start();
DownloadTextButton=(Button)findViewById(R.id.DownTextButtonId);
DownloadTextButton.setOnClickListener(newDownTextButtonListener());
DownloadMp3Button=(Button)findViewById(R.id.DownMp3ButtonId);
DownloadMp3Button.setOnClickListener(newDownMp3ButtonListener());
}
privateclassDownTextButtonListenerimplementsOnClickListener
{
publicvoidonClick(Viewv)
{
Threadthread=newThread(newRunnable()
{
publicvoidrun()
{
//TODOAuto-generatedmethodstub
HttpDownloaderhttpDownloader=newHttpDownloader();
Stringirc=httpDownloader
.download("http:
//下载路径",);
System.out.println(irc);
}
});
thread.start();
}
}
privateclassDownMp3ButtonListenerimplementsOnClickListener
{
publicvoidonClick(Viewv)
{
Threadthread=newThread(newRunnable()
{
publicvoidrun()
{
//TODOAuto-generatedmethodstub
HttpDownloaderhttpDownloader=newHttpDownloader();
intresult=httpDownloader
.downFile(
"http:
//下载路径",,
"test/","love.exe");
System.out.println(result);
}
});
thread.start();
}
}
}
packagecom.download;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
import.HttpURLConnection;
import.MalformedURLException;
import.URL;
import.URLConnection;
importandroid.util.Log;
publicclassHttpDownloader
{
privateURLurl=null;
publicStringdownload(StringurlStr)
{
StringBuffersb=newStringBuffer();
Stringline=null;
BufferedReaderbuffer=null;
try
{
//创建一个url对象
url=newURL(urlStr);
//创建一个Http连接对象
//HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();
URLConnectionurlConn=url.openConnection();
urlConn.connect();
intfileSize=urlConn.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();
}
}
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,
inputStream);
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-generatedmethodstub
url=newURL(urlStr);
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.os.Environment;
publicclassFileUtils
{
privateStringSDPATH;
publicStringgetSDPATH()
{
returnSDPATH;
}
publicFileUtils()
{
SDPATH=Environment.getExternalStorageDirectory()+"/";
}
publicFilecreateSDFile(Stringfilename)throwsIOException
{
Filefile=newFile(SDPATH+filename);
file.createNewFile();
returnfile;
}
publicFilecreateSDDir(Stringdirname)throwsIOException
{
Filefile=newFile(SDPATH+dirname);
file.mkdir();
returnfile;
}
publicbooleanisFileExist(StringfileName)
{
Filefile=newFile(SDPATH+fileName);
returnfile.exists();
}
publicFilewrite2SDFromInput(Stringpath,StringfileName,
InputStreaminput)
{
Filefile=null;
OutputStreamoutput=null;
try
{
createSDDir(path);
file=createSDFile(path+fileName);
output=newFileOutputStream(file);
bytebuffer[]=newbyte[4*1024];
while((input.read(buffer))!
=-1)
{
output.write(buffer);
}
output.flush();
}catch(Exceptione)
{
e.printStackTrace();
}finally
{
try
{
output.close();
}catch(Exceptione)
{
e.printStackTrace();
}
}
returnfile;
}
}
Main.xml
xmlversion="1.0"encoding="utf-8"?
>
android="
android:
orientation="vertical"
android:
layout_width="fill_parent"
android:
layout_height="fill_parent"
>
android:
layout_width="fill_parent"
android:
layout_height="wrap_content"
android:
text="@string/hello"
/>
id="@+id/tv"
android:
layout_width="fill_parent"
android:
layout_height="wrap_content"
android:
text=""
/>
id="@+id/down_pb"
android:
layout_width="fill_parent"
android:
layout_height="wrap_content"
android:
max="100"
style="?
android:
attr/progressBarStyleHorizontal"
/>