android文件下载及进度条Word文件下载.docx
《android文件下载及进度条Word文件下载.docx》由会员分享,可在线阅读,更多相关《android文件下载及进度条Word文件下载.docx(14页珍藏版)》请在冰豆网上搜索。
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();
case-1:
Stringerror=msg.getData().getString("
error"
Toast.makeText(AndroidDownLoadActivity.this,error,1)
}
}
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)
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);
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)
}.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("
);
System.out.println(irc);
});
thread.start();
privateclassDownMp3ButtonListenerimplementsOnClickListener
intresult=httpDownloader
.downFile(
"
,
"
test/"
love.exe"
System.out.println(result);
}
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
import.HttpURLConnection;
import.MalformedURLException;
publicclassHttpDownloader
privateURLurl=null;
publicStringdownload(StringurlStr)
StringBuffersb=newStringBuffer();
Stringline=null;
BufferedReaderbuffer=null;
//创建一个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;
FileUtilsfileUtils=newFileUtils();
if(fileUtils.isFileExist(path+fileName))
return1;
}else
inputStream=getInputStreamFromUrl(urlStr);
FileresultFile=fileUtils.write2SDFromInput(path,fileName,
inputStream);
if(resultFile==null)
return-1;
return-1;
inputStream.close();
return0;
privateInputStreamgetInputStreamFromUrl(StringurlStr)
throwsMalformedURLException,IOException
//TODOAuto-generatedmethodstub
url=newURL(urlStr);
HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();
InputStreaminputStream=urlConn.getInputStream();
returninputStream;
importjava.io.OutputStream;
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();
publicbooleanisFileExist(StringfileName)
Filefile=newFile(SDPATH+fileName);
returnfile.exists();
publicFilewrite2SDFromInput(Stringpath,StringfileName,
InputStreaminput)
Filefile=null;
OutputStreamoutput=null;
createSDDir(path);
file=createSDFile(path+fileName);
output=newFileOutputStream(file);
bytebuffer[]=newbyte[4*1024];
while((input.read(buffer))!
=-1)
output.write(buffer);
output.flush();
output.close();
Main.xml
<
?
xmlversion="
1.0"
encoding="
utf-8"
>
LinearLayoutxmlns:
android="
android:
orientation="
vertical"
layout_width="
fill_parent"
layout_height="
>
TextView
wrap_content"
text="
@string/hello"
/>
TextViewandroid:
id="
@+id/tv"
android:
"
/>
ProgressBarandroid:
@+id/down_pb"
max="
100"
style="
attr/progressBarStyleHorizontal"
Button
@+id/DownTextButtonId"
DownloadText"
@+id/DownMp3ButtonId"
DownloadMp3"
/LinearLayout>
Manifest.xml
manifestxmlns:
package="
com.download"
versionCode="
1"
versionName="
<
uses-sdkandroid:
minSdkVersion="
11"
uses-permissionandroid:
name="
android.permission.WRITE_EXTERNAL_STORAGE"
/uses-permission>
android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
/us