欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中实现下载URL地址的网络资源的实例分享

程序员文章站 2024-03-01 18:40:58
通过url来获取网络资源并下载资源简单实例: package com.android.xiong.urltest; import java.io.i...

通过url来获取网络资源并下载资源简单实例:

package com.android.xiong.urltest; 
 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.outputstream; 
import java.net.malformedurlexception; 
import java.net.url; 
 
import android.app.activity; 
import android.graphics.bitmap; 
import android.graphics.bitmapfactory; 
import android.os.bundle; 
import android.os.handler; 
import android.os.message; 
import android.view.menu; 
import android.widget.imageview; 
 
public class mainactivity extends activity { 
  imageview show; 
  bitmap bitmap; 
  handler handler = new handler() { 
 
    @override 
    public void handlemessage(message msg) { 
      if (msg.what == 0x123) { 
        // 使用imageview显示该图片 
        show.setimagebitmap(bitmap); 
 
      } 
    } 
 
  }; 
 
  @override 
  protected void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.activity_main); 
    show = (imageview) findviewbyid(r.id.show); 
 
    new thread() { 
 
      @override 
      public void run() { 
        // 定义一个url对象 
        url url; 
        try { 
          url = new url( 
              "http://img1.gtimg.com/news/pics/hv1/37/195/1468/95506462.jpg"); 
          // 打开该url的资源输入流 
          inputstream is = url.openstream(); 
          // 从inputstream中解析出图片 
          bitmap = bitmapfactory.decodestream(is); 
          // 发送消息 
          handler.sendemptymessage(0x123); 
          is.close(); 
          // 再次打开rl对应的资源输入流 
          is = url.openstream(); 
          // 打开手机文件对应的输出流 
          outputstream os = openfileoutput("keqiang.jpg", mode_append); 
          byte[] buff = new byte[1024]; 
          int hasread = 0; 
          // 将url资源下载到本地 
          while ((hasread = is.read(buff)) > 0) { 
            os.write(buff, 0, hasread); 
          } 
          is.close(); 
          os.close(); 
        } catch (malformedurlexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } catch (ioexception e) { 
          // todo auto-generated catch block 
          e.printstacktrace(); 
        } 
 
      } 
 
    }.start(); 
  } 
 
  @override 
  public boolean oncreateoptionsmenu(menu menu) { 
    // inflate the menu; this adds items to the action bar if it is present. 
    getmenuinflater().inflate(r.menu.main, menu); 
    return true; 
  } 
 
} 
<linearlayout xmlns: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> 

网络资源多线程下载:

package com.example.threaddown; 
 
import java.util.timer; 
import java.util.timertask; 
 
import android.app.activity; 
import android.os.bundle; 
import android.os.handler; 
import android.os.message; 
import android.view.menu; 
import android.view.view; 
import android.view.view.onclicklistener; 
import android.widget.button; 
import android.widget.edittext; 
import android.widget.progressbar; 
 
public class mainactivity extends activity { 
 
  edittext url; 
  edittext target; 
  button downbn; 
  progressbar bar; 
  downutil downutil; 
  private int mdownstatus; 
 
  @override 
  protected void oncreate(bundle savedinstancestate) { 
    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对象 
    final handler handler = new handler() { 
 
      @override 
      public void handlemessage(message msg) { 
        if (msg.what == 0x123) { 
          bar.setprogress(mdownstatus); 
        } 
      } 
 
    }; 
    downbn.setonclicklistener(new onclicklistener() { 
 
      @override 
      public void onclick(view v) { 
        // 初始化downutil对象 
        downutil = new downutil(url.gettext().tostring(), target 
            .gettext().tostring(), 6); 
        new thread() { 
 
          @override 
          public void run() { 
            try { 
              // 开始下载 
              downutil.download(); 
 
            } catch (exception e) { 
              e.printstacktrace(); 
            } 
            // 定义每秒调度获取一次系统的完成进度 
            final timer timer = new timer(); 
            timer.schedule(new timertask() { 
 
              @override 
              public void run() { 
                // 获取下载任务的完成比例 
                double completerate = downutil 
                    .getcompleterate(); 
                mdownstatus = (int) (completerate * 1000); 
                // 发送消息通知届满更新的进度条 
                handler.sendemptymessage(0x123); 
                // 下载完成之后取消任务进度 
                if (mdownstatus >= 100) { 
                  timer.cancel(); 
                } 
              } 
            }, 0, 1000); 
          } 
 
        }.start(); 
      } 
    }); 
  } 
 
  @override 
  public boolean oncreateoptionsmenu(menu menu) { 
    // inflate the menu; this adds items to the action bar if it is present. 
    getmenuinflater().inflate(r.menu.main, menu); 
    return true; 
  } 
 
} 
package com.example.threaddown; 
 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.randomaccessfile; 
import java.net.httpurlconnection; 
import java.net.malformedurlexception; 
import java.net.url; 
 
public class downutil { 
 
  // 定义下载资源的路径 
  private string path; 
  // 指定所下载的文件的保存位置 
  private string targetfile; 
  // 定义需要使用多少线程下载资源 
  private int threadnum; 
  // 定义下载的线程对象 
  private downthread[] threads; 
  // 定义下载的文件总大小 
  private int filesize; 
 
  public downutil(string path, string targetfile, int threadnum) { 
    this.path = path; 
    this.targetfile = targetfile; 
    this.threadnum = threadnum; 
  } 
 
  public void download() throws ioexception { 
    url url = new url(path); 
    httpurlconnection conn = (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(); 
    int currentpartssize = filesize / threadnum + 1; 
    randomaccessfile file = new randomaccessfile(targetfile, "rw"); 
    // 设置本地文件的大小 
    file.setlength(filesize); 
    file.close(); 
    for (int i = 0; i < threadnum; i++) { 
      // 计算每条线程的下载位置 
      int startpos = i * currentpartssize; 
      // 每个线程使用一个randomaccessfile进行下载 
      randomaccessfile current = new randomaccessfile(targetfile, "rw"); 
      // 定义该线程的下载位置 
      current.seek(startpos); 
      // 创建下载线程 
      threads[i] = new downthread(startpos, currentpartssize, current); 
      // 启动线程下载 
      threads[i].start(); 
    } 
 
  } 
 
  // 获取下载的完成百分比 
  public double getcompleterate() { 
    // 统计多条线程已经下载的总大小 
    int sumsize = 0; 
    for (int i = 0; i < threadnum; i++) { 
      sumsize += threads[i].length; 
    } 
    return sumsize * 1.0 / filesize; 
  } 
 
  private class downthread extends thread { 
    // 定义当前线程下载的位置 
    private int startpos; 
    // 定义当前线程下载文件的大小 
    private int currentpartssize; 
    // 当前线程下载的文件块 
    private randomaccessfile currentpart; 
    // 定义该线程已下载的字节数 
    private int length; 
 
    public downthread(int startpos, int currentpartssize, 
        randomaccessfile currentpart) { 
      this.startpos = startpos; 
      this.currentpart = currentpart; 
      this.currentpartssize = currentpartssize; 
 
    } 
 
    @override 
    public void run() { 
      try { 
        url url = new url(path); 
        httpurlconnection conn = (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"); 
        inputstream in = conn.getinputstream(); 
        in.skip(startpos); 
        int hasread = 0; 
        byte[] buffer = new byte[1024]; 
        // 读取网络数据,并写入本地文件 
        while (length < currentpartssize 
            && (hasread = in.read(buffer)) > 0) { 
          currentpart.write(buffer, 0, hasread); 
          // 累计该线程下载的总大小 
          length += hasread; 
        } 
        currentpart.close(); 
        in.close(); 
 
      } catch (exception e) { 
        e.printstacktrace(); 
      } 
 
    } 
 
  } 
 
} 


<linearlayout xmlns: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-permission android:name="android.permission.mount_unmount_filesystems" /> 
<!-- 在sd开中写入数据的权限 --> 
<uses-permission android:name="android.permission.write_external_storage" /> 
<!-- 访问网路的权限 --> 
<uses-permission android:name="android.permission.internet" />