Android programming development implements multithreaded downloads with progress bars and percentages _android

Source: Internet
Author: User
Tags flush gettext int size

This article describes the Android programming development implementation with a progress bar and a percentage of multithreaded downloads. Share to everyone for your reference, specific as follows:

Following the previous "Java Multithreading download instance detailed", it can be transplanted into our Android, the following is the specific implementation of the source code:

Downactivity.java:

Package com.example.downloads;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.RandomAccessFile;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Com.example.downloads.utils.DownLoadThread;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.annotation.SuppressLint;
Import android.app.Activity;
Import Android.text.TextUtils;
Import Android.view.Menu;
Import Android.view.View;
Import Android.widget.EditText;
Import Android.widget.ProgressBar;
Import Android.widget.TextView;
Import Android.widget.Toast;
  The public class Downactivity extends the activity {//declares the control/path to the number of threads public edittext et_url, Et_num;
  Progress bar public static ProgressBar Pb_thread;
  Displays the progress of the operation public TextView TV_PB;
  Number of threads public static int threadnum = 3;
  Each thread is responsible for downloading the size of the public int blockSize;
 public static int threadcount;//number//access path public String path; public static Boolean flag = TRUE;
  Record the value of the progress bar public static int pb_count = 0;
  public static Handler Handler;
  public static final int textvalue = 1;
  public static int pb_num = 0;
  public static int size = 0;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_down);
    Et_url = (edittext) Findviewbyid (R.id.et_path);
    Et_num = (edittext) Findviewbyid (r.id.et_threadnum);
    Pb_thread = (ProgressBar) Findviewbyid (R.id.pb_down);
    TV_PB = (TextView) Findviewbyid (R.ID.TV_PB); Handler = new Handler () {@SuppressLint ("Handlerleak") @Override public void Handlemessage (msg)
        {super.handlemessage (msg);  Switch (msg.what) {case TEXTVALUE:System.out.println ("-------" + Downactivity.pb_count +
          "//////" + downactivity.size); Change TextView pb_num = (Downactivity.pb_count *)/downactivity.siZe
          Tv_pb.settext ("Current progress is +" + pb_num + "%");
        Break
        Default:break;
  }
      }
    };  @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;
    public void DownLoad (View v) {Downactivity.flag = true;
    Downactivity.pb_count = 0;
    Path = Et_url.gettext (). toString ();
    String Threadnum_et = Et_num.gettext (). toString (); if (textutils.isempty (path) | |
      Textutils.isempty (Threadnum_et)) {Toast.maketext (this, cannot be empty, Toast.length_long). Show ();
    Return
    Toast.maketext (This, "URL:" + path + "--" + Threadnum_et, Toast.length_long). Show ();
    Convert to Digital threadnum = integer.valueof (Threadnum_et); New Thread (New Runnable () {@Override public void run () {try {//Create URL object url ur
          L = new URL (path); //Creates a HttpURLConnection object httpurlconnection httpurlconnection = (httpurlconnection) URL. openconnect
          Ion ();
          Set the way the send request is sent Httpurlconnection.setrequestmethod ("get");
          Sets whether the request is timed out httpurlconnection.setconnecttimeout (5000); Set HttpURLConnection. Setrequestproperty ("User-agent", "mozilla/5.0" (Compati ble MSIE 10.0; Windows NT 6.2;
          trident/6.0) "); Whether to respond to success if (httpurlconnection.getresponsecode () = = 200) {//Get the size of the file = Httpurlcon
            Nection.getcontentlength ();
            SYSTEM.OUT.PRINTLN ("Size of file" + sizes);
            Set the maximum value of the progress bar Pb_thread.setmax (size);
                Create File//save to SD card//First determine if you have SDcard if (environment.getexternalstoragestate (). Equals (
                  environment.media_mounted)) {//Get SDcard File directory object File Sdfile = Environment . getexterNalstoragedirectory ();
              Creates a file object, filename = new file (sdfile, "Youdao.exe");
              Randomaccessfile accessfile = new Randomaccessfile (file, "RWD");
              Sets the size of the file (accessfile.setlength);
              The size blockSize = size/threadnum per thread download; Open three threads to manipulate this file for (int i = 1; I <= threadnum i++) {//1 2 3//COMPUTE each thread
                The starting position int startsize = (i-1) * blockSize;
                End position int endsize = (i) * blockSize; If the thread is the last thread if (i = = threadnum) {//Determines whether the file size is greater than the computed end position if (siz
                  E > Endsize) {//End position equals file size endsize = size; Create a random read for each thread randomaccessfile threadaccessfile = new randomaccess
                  File (  File, "RWD"); New Thread (New Downloadthread (I, Threadaccessfile, startsize, endsize, Path)). Star
              T ();
        catch (Malformedurlexception e) {e.printstacktrace ()}}};
        catch (IOException e) {e.printstacktrace ();
  }}). Start (); /** * Suspend Operation * * @param v/public void Downpause (View v) {Toast.maketext (this, pause, toast.length_l
    ONG). Show ();
  This.flag = false;

 }
}

Downloadthread.java:

Package com.example.downloads.utils;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.RandomAccessFile;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import com.example.downloads.DownActivity;
Import android.os.Environment; public class Downloadthread implements Runnable {public randomaccessfile accessfile;//Each thread has a Accessfile file object thread 1 line
  Path 2 thread 3//thread download file starting position public int startsize;
  public int endsize;
  The path path to the file download is public String path; public int threadId;  Identification of threads public downloadthread (int threadId, randomaccessfile accessfile, int startsize, int endsize, String path)
    {this.threadid = threadId;
    This.accessfile = Accessfile;
    This.startsize = startsize;
    This.endsize = endsize;
  This.path = path; @Override public void Run () {//Execute Run Method try {///create file to SD card//FirstFirst, determine if you have SDcard if (environment.getexternalstoragestate (). Equals (environment.media_mounted)) {//obtained
        Fetch sdcard File directory object Files Sdfile = Environment.getexternalstoragedirectory ();
        File Threadfile = new file (sdfile, ThreadId + ". txt"); if (threadfile.exists ()) {//Read the contents of the file//create the input stream object of the file FileInputStream fis = new Fileinputstre
          AM (Threadfile);
          Using the tool class to read byte data[] = Streamtools.istodata (FIS);
          Convert to String threadlen = new string (data); if (Threadlen!= null) && (! "".
            Equals (Threadlen))) {startsize = integer.valueof (Threadlen);
            Fix 416bug Error if (Startsize > endsize) {startsize = endSize-1;
        }///create File//Create URL object url url = new URL (path);
           Create HttpURLConnection object HttpURLConnection httpurlconnection = (httpurlconnection) URL . OpenConnection ();
        Sets the requested header Httpurlconnection.setrequestmethod ("get");
        Sets whether the request is timed out httpurlconnection.setconnecttimeout (5000); Set HttpURLConnection. Setrequestproperty ("User-agent", "mozilla/5.0" (compatible; MSIE 10.0; Windows NT 6.2;
        trident/6.0) ");
        Key Settings Httpurlconnection.setrequestproperty ("Range", "bytes=" + startsize + "-" + endsize);
        Output Current thread System.out.println ("Current thread" + threadId + "Download start position:" + startsize + "Download End Position:" + endsize);
        Response Success//Set the starting position of the random read file Accessfile.seek (startsize);
        Gets the corresponding stream object InputStream is = Httpurlconnection.getinputstream ();
        Create output stream object byte buffer[] = new byte[1024];
        int len = 0;  int threadtotal = 0;//Save Record/while (len = is.read (buffer)!=-1) {accessfile.write (buffer, 0) after each thread downloads
          Len); Threadtotal + = len;//Record the length of your writing//xML file//Change progress bar: Setprogressbar (len);
          FileOutputStream fos = new FileOutputStream (threadfile) by the length of the download of the file record file
          Fos.write ((Threadtotal + ""). GetBytes ());
          Fos.flush ();
          Fos.close ();
          Send Handler message DownActivity.handler.sendEmptyMessage (Downactivity.textvalue); if (!
          Downactivity.flag) {return;
        } accessfile.close ();
        Is.close ();
        System.out.println (threadId + "thread execution complete");
          Thread operation synchronized (Downactivity.class) {downactivity.threadcount++; if (Downactivity.threadcount >= downactivity.threadnum) {for (int i = 1; I <= downactivity.threadnum; i
              + +) {//Get the file on sdcard = DeleteFile = new file (sdfile, i + ". txt");
              if (deletefile.exists ()) {//File deletion deletefile.delete ();
 }
            }
          }
        }     The catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace ();
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
    } public synchronized void Setprogressbar (int len) {downactivity.pb_count+=len;
  DownActivity.pb_thread.setProgress (Downactivity.pb_count);

 }
}

Streamtools.java:

Package com.example.downloads.utils;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
public class Streamtools {public
  static byte[] Istodata (InputStream is) throws ioexception{
    /byte output stream
    Bytearrayoutputstream Bops = new Bytearrayoutputstream ();
    Cache
    byte buffer[] = new byte[1024] = read data;
    Read the length of the record
    int len = 0;
    Loop read
    while (len = is.read (buffer))!=-1) {
      bops.write (buffer, 0, Len);
    }
    Converts the read content to byte array
    byte data[] = Bops.tobytearray ();
    Bops.flush ();
    Bops.close ();
    Is.close ();
    return data;
  }


Strings.xml:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
  <string name= "App_name" >downloads </string>
  <string name= "action_settings" >Settings</string>
  <string name= "Tv_down" > File Download Address </string>
  <string name= "tv_threadnum" > Thread quantity </string>
  <string name= "Tv_num ">0%</string>
  <string name=" btn_text "> Download </string>
  <string name=" Btn_pause "> Suspend </string>
  <string name= "Et_path" >http://172.22.64.8:8080/doudou/youdao.exe</string>
  <string name= "Et_threadnum" >3</string>
</resources>

Layout file:

<relativelayout 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: paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Downactivity "> <textview android:id=" @+id/textview1 "android:layout_width=" Wrap_content "Android:layo" ut_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_alignparenttop= "true" Android:te xt= "@string/tv_down"/> <edittext android:id= "@+id/et_path" android:layout_width= "Wrap_content" Androi d:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_alignparentright= "true" an
  droid:layout_below= "@+id/textview1" android:ems= "10"  Android:inputtype= "None" android:text= "@string/et_path" > <requestfocus/> </EditText> <te
    Xtview android:id= "@+id/textview2" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_alignparentleft= "true" android:layout_below= "@+id/et_path" android:text= "@string/tv_threadnum"/&
  Gt <edittext android:id= "@+id/et_threadnum" android:layout_width= wrap_content "android:layout_height=" Wrap_co Ntent "android:layout_alignleft=" @+id/textview2 "android:layout_alignright=" @+id/et_path "Android:layout_below" = "@+id/textview2" android:ems= "ten" android:inputtype= "number" android:text= "@string/et_threadnum"/> < ProgressBar android:id= "@+id/pb_down" style= "Android:attr/progressbarstylehorizontal" W Rap_content "android:layout_height=" wrap_content "android:layout_alignleft=" @+id/et_threadnum "Android:layout_" Alignright= "@+id/eT_threadnum "android:layout_below=" @+id/et_threadnum "android:layout_margintop=" 14DP "/> <TextView and Roid:id= "@+id/tv_pb" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_a lignright= "@+id/textview1" android:layout_below= "@+id/pb_down" android:layout_margintop= "24DP" android:text= "@ String/tv_num "/> <button android:id= @+id/btn_down" android:layout_width= "Wrap_content" android:layou t_height= "Wrap_content" android:layout_alignleft= "@+id/pb_down" android:layout_below= "@+id/tv_pb" Android:layo ut_margintop= "32DP" android:onclick= "DownLoad" android:text= "@string/btn_text"/> <button android:id= " @+id/button1 "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:layout_alignLef" t= "@+id/btn_down" android:layout_below= "@+id/btn_down" android:layout_margintop= "16DP" android:onclick= "DownPa" Use "android:text=" @String/btn_pause "/> </RelativeLayout>

 

The effect is as follows:

The last thing to note is that you should not forget to add permissions to the project manifest file:

<!--sdcard permissions-->
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--permissions to access the network-->
<uses-permission android:name= "Android.permission.INTERNET"/>

I hope this article will help you with the Android program.

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.