Android中实现下载URL地址的网络资源的实例分享
通过URL来获取网络资源并下载资源简单实例:
packagecom.android.xiong.urltest;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.net.MalformedURLException;
importjava.net.URL;
importandroid.app.Activity;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.view.Menu;
importandroid.widget.ImageView;
publicclassMainActivityextendsActivity{
ImageViewshow;
Bitmapbitmap;
Handlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
if(msg.what==0x123){
//使用ImageView显示该图片
show.setImageBitmap(bitmap);
}
}
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show=(ImageView)findViewById(R.id.show);
newThread(){
@Override
publicvoidrun(){
//定义一个URL对象
URLurl;
try{
url=newURL(
"http://img1.gtimg.com/news/pics/hv1/37/195/1468/95506462.jpg");
//打开该URL的资源输入流
InputStreamis=url.openStream();
//从InputStream中解析出图片
bitmap=BitmapFactory.decodeStream(is);
//发送消息
handler.sendEmptyMessage(0x123);
is.close();
//再次打开RL对应的资源输入流
is=url.openStream();
//打开手机文件对应的输出流
OutputStreamos=openFileOutput("KEQIANG.JPG",MODE_APPEND);
byte[]buff=newbyte[1024];
inthasRead=0;
//将URL资源下载到本地
while((hasRead=is.read(buff))>0){
os.write(buff,0,hasRead);
}
is.close();
os.close();
}catch(MalformedURLExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}.start();
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ImageView android:id="@+id/show" android:layout_width="match_parent" android:layout_height="match_parent" android:contentDescription="@string/hello_world"/> </LinearLayout>
网络资源多线程下载:
packagecom.example.threaddown;
importjava.util.Timer;
importjava.util.TimerTask;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.view.Menu;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.ProgressBar;
publicclassMainActivityextendsActivity{
EditTexturl;
EditTexttarget;
ButtondownBn;
ProgressBarbar;
DownUtildownUtil;
privateintmDownStatus;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取程序界面中的三个界面控制
url=(EditText)findViewById(R.id.url);
target=(EditText)findViewById(R.id.target);
downBn=(Button)findViewById(R.id.downBn);
bar=(ProgressBar)findViewById(R.id.br);
//创建一个Handler对象
finalHandlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
if(msg.what==0x123){
bar.setProgress(mDownStatus);
}
}
};
downBn.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
//初始化DownUtil对象
downUtil=newDownUtil(url.getText().toString(),target
.getText().toString(),6);
newThread(){
@Override
publicvoidrun(){
try{
//开始下载
downUtil.download();
}catch(Exceptione){
e.printStackTrace();
}
//定义每秒调度获取一次系统的完成进度
finalTimertimer=newTimer();
timer.schedule(newTimerTask(){
@Override
publicvoidrun(){
//获取下载任务的完成比例
doublecompleteRate=downUtil
.getCompleteRate();
mDownStatus=(int)(completeRate*1000);
//发送消息通知届满更新的进度条
handler.sendEmptyMessage(0x123);
//下载完成之后取消任务进度
if(mDownStatus>=100){
timer.cancel();
}
}
},0,1000);
}
}.start();
}
});
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}
packagecom.example.threaddown;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.RandomAccessFile;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URL;
publicclassDownUtil{
//定义下载资源的路径
privateStringpath;
//指定所下载的文件的保存位置
privateStringtargetFile;
//定义需要使用多少线程下载资源
privateintthreadNum;
//定义下载的线程对象
privateDownThread[]threads;
//定义下载的文件总大小
privateintfileSize;
publicDownUtil(Stringpath,StringtargetFile,intthreadNum){
this.path=path;
this.targetFile=targetFile;
this.threadNum=threadNum;
}
publicvoiddownload()throwsIOException{
URLurl=newURL(path);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept","*/*");
conn.setRequestProperty("Accept-Language","zh-CN");
conn.setRequestProperty("Charset","UTF-8");
conn.setRequestProperty("Connection","Keep-Alive");
//得到文件的大小
fileSize=conn.getContentLength();
conn.disconnect();
intcurrentPartsSize=fileSize/threadNum+1;
RandomAccessFilefile=newRandomAccessFile(targetFile,"rw");
//设置本地文件的大小
file.setLength(fileSize);
file.close();
for(inti=0;i<threadNum;i++){
//计算每条线程的下载位置
intstartPos=i*currentPartsSize;
//每个线程使用一个RandomAccessFile进行下载
RandomAccessFilecurrent=newRandomAccessFile(targetFile,"rw");
//定义该线程的下载位置
current.seek(startPos);
//创建下载线程
threads[i]=newDownThread(startPos,currentPartsSize,current);
//启动线程下载
threads[i].start();
}
}
//获取下载的完成百分比
publicdoublegetCompleteRate(){
//统计多条线程已经下载的总大小
intsumSize=0;
for(inti=0;i<threadNum;i++){
sumSize+=threads[i].length;
}
returnsumSize*1.0/fileSize;
}
privateclassDownThreadextendsThread{
//定义当前线程下载的位置
privateintstartPos;
//定义当前线程下载文件的大小
privateintcurrentPartsSize;
//当前线程下载的文件块
privateRandomAccessFilecurrentPart;
//定义该线程已下载的字节数
privateintlength;
publicDownThread(intstartPos,intcurrentPartsSize,
RandomAccessFilecurrentPart){
this.startPos=startPos;
this.currentPart=currentPart;
this.currentPartsSize=currentPartsSize;
}
@Override
publicvoidrun(){
try{
URLurl=newURL(path);
HttpURLConnectionconn=(HttpURLConnection)url
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept","*/*");
conn.setRequestProperty("Accept-Language","zh-CN");
conn.setRequestProperty("Charset","UTF-8");
conn.setRequestProperty("Connection","Keep-Alive");
InputStreamin=conn.getInputStream();
in.skip(startPos);
inthasRead=0;
byte[]buffer=newbyte[1024];
//读取网络数据,并写入本地文件
while(length<currentPartsSize
&&(hasRead=in.read(buffer))>0){
currentPart.write(buffer,0,hasRead);
//累计该线程下载的总大小
length+=hasRead;
}
currentPart.close();
in.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}
}
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/url" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="http://ksoap2-android.googlecode.com/svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/3.1.0/ksoap2-android-assembly-3.1.0-jar-with-dependencies.jar"/> <EditText android:id="@+id/target" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="/mnt/sdcard/"/> <Button android:id="@+id/downBn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="down"/> <ProgressBar android:id="@+id/br" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>
<!--在SD卡中创建与删除文件的权限--> <uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--在SD开中写入数据的权限--> <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!--访问网路的权限--> <uses-permissionandroid:name="android.permission.INTERNET"/>