An example sharing of network resources for downloading URL addresses in Android _android

Source: Internet
Author: User
Tags gettext

to obtain network resources through a URL and download a simple instance of a resource:

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 (msg) {if (Msg.what = 0x 
 
      123) {///use ImageView to display the picture 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 () {//Defines a URL object URL url; 
          try {url = new URL ("Yun_qi_img/95506462.jpg"); 
          The resource input stream that opens the URL inputstream is = Url.openstream (); 
          The picture bitmap = Bitmapfactory.decodestream (IS) was parsed from the InputStream. 
          Send Message Handler.sendemptymessage (0x123); 
          Is.close (); 
          Again open RL corresponding resource input stream is = Url.openstream (); Open the phone file corresponding to the output stream outputstream OS = Openfileoutput ("Keqiang.") 
          JPG ", mode_append); 
          byte[] buff = new byte[1024]; 
          int hasread = 0; 
          Downloads the URL resource to the local 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 Actio 
    n 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> 

Multi-threaded download of network resources:

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); 
    Gets the three interface control URLs in the program interface = (edittext) Findviewbyid (R.id.url); 
    target = (edittext) Findviewbyid (r.id.target); 
    DOWNBN = (Button) Findviewbyid (R.ID.DOWNBN); 
    Bar = (ProgressBar) Findviewbyid (r.id.br); Create a Handler object final Handler Handler = new Handler () {@Override public void Handlemessage (msg) {if (Msg.what = = 0x123) { 
        Bar.setprogress (Mdownstatus); 
    } 
      } 
 
    }; Downbn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//Initialize D 
        Ownutil Object downutil = new Downutil (Url.gettext (). ToString (), Target. GetText (). ToString (), 6); 
              New Thread () {@Override public void run () {try {//start download 
 
            Downutil.download (); 
            catch (Exception e) {e.printstacktrace (); 
            //define the completion schedule per second of the system to receive the final timer timer = new timer (); Timer.schedule (New TimerTask () {@Override public void run () {//Get download task's 
          Percent Complete Double completerate = downutil. Getcompleterate ();      Mdownstatus = (int) (completerate * 1000); 
                Send a message to notify the expiration of the updated progress bar handler.sendemptymessage (0x123); 
                Cancel task Progress after download completes if (Mdownstatus >=) {timer.cancel (); 
          }}, 0, 1000); 
      }}.start (); 
  } 
    }); @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio 
    n 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 {//define the path of the download resource private String path; 
  Specifies the location where the downloaded file is saved private String targetfile; 
  Define how many threads to use to download resources private int threadnum; 
  Define the downloaded thread object private downthread[] threads; 
 
  Defines the total size of the downloaded file private int fileSize; 
    Public Downutil (string path, string targetfile, int threadnum) {this.path = path; 
    This.targetfile = TargetFile; 
  This.threadnum = Threadnum; 
    The 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"); 
    Get the size of the file FileSize = Conn.getcontentlength (); 
    Conn.disconnect (); 
    int currentpartssize = filesize/threadnum + 1; 
    Randomaccessfile file = new Randomaccessfile (targetfile, "RW"); 
    Sets the size of the local file File.setlength (fileSize); 
    File.close (); 
      for (int i = 0; i < threadnum i++) {//Compute the download location of each thread int startpos = i * currentpartssize; 
      Each thread uses a randomaccessfile to download randomaccessfile current = new Randomaccessfile (targetfile, "RW"); 
      Define the download location of the thread Current.seek (startpos); 
      Create download thread Threads[i] = new Downthread (startpos, currentpartssize, current); 
    Start thread download Threads[i].start (); 
    //Get percent Complete of download public double getcompleterate () {///Statistics The total size of multiple threads already downloaded int sumsize = 0; 
    for (int i = 0; i < threadnum i++) {sumsize + = Threads[i].length; Return sumsize * 1.0/FILesize; 
    Private class Downthread extends thread {//define the location of the current thread download private int startpos; 
    Defines the size of the current thread download file private int currentpartssize; 
    The current thread downloads the file block private randomaccessfile Currentpart; 
 
    Defines the number of bytes that this thread has downloaded private int length; Public downthread (int startpos, int currentpartssize, Randomaccessfile currentpart) {this.startpos = Star 
      TPOs; 
      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];  Read network data and write local files while (length < currentpartssize && (Hasread = in.read (buffer)) > 0) 
          {currentpart.write (buffer, 0, hasread); 
        Cumulative total size length + = Hasread for this thread download; 
        } 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:orien" tation= "Vertical" tools:context= ". Mainactivity "> <edittext android:id=" @+id/url "android:layout_width=" Match_parent "Android:layo" ut_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= NT "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 "/>" 

 Lt;/linearlayout>
 <!--Create and delete files in SD cards--> <uses-permission android:name= " Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/> <!--permissions to write data in SD--> <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/> <!--access network permissions--> <uses-permission android:name=" Android.permission.INTERNET "/> 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.