Android uses StartService to download files in bulk _android

Source: Internet
Author: User
Tags file url

For a basic overview of the use of StartService and its lifecycle, see Overview of basic usage of StartService in Android.

This article demonstrates the use of StartService and StopService (Startid) through a simple example of bulk downloading of files, as follows

The system interface is as follows:

The interface is very simple, just a button "bulk download article", the activity on the button to start Downloadservice.

Downloadservice is used to download Csdn blog posts on the service, the code is as follows:

Package Com.ispring.startservicedemo;
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.Handler;
Import Android.os.IBinder;
Import Android.os.Message;
Import Android.util.Log;

Import Android.widget.Toast;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.util.ArrayList;

Import java.util.List; public class Downloadservice extends Service {//store all Startid private list<integer> allstartidlist = new Arrayli
  St<> ();

  Store already downloaded Startid private list<integer> finishedstartidlist = new arraylist<> (); Private Handler Handler = new Handler () {@Override public void Handlemessage (msg) {if (Msg.what = 1
        ) {String tip = (string) msg.obj;
      Toast.maketext (Downloadservice.this, Tip, Toast.length_long). Show ();

  }
    }
  }; Class Downloadthread extends Thread {//Correspondence Intent Startid LetterInterest-private int startid = 0;

    The article name to download private String blogname = null;

    To download the article address private String blogurl = null;
      Public downloadthread (int startid, string name, string url) {This.startid = Startid;
      This.blogname = name;
    This.blogurl = URL;
      @Override public void Run () {HttpURLConnection conn = null;
      InputStream is = null;
        try{//Download the specified file URL url = new URL (this.blogurl);
        conn = (httpurlconnection) url.openconnection (); IF (conn!= null) {//Where we get the input stream for the downloaded article, we can write it as a file to the memory card or///read the text out of the app to display it in the app. = Conn.getinput
        Stream ();
      }}catch (Malformedurlexception e) {e.printstacktrace ();
      }catch (IOException e) {e.printstacktrace ();
        }finally {if (conn!= null) {conn.disconnect ();

      } finishedstartidlist.add (Startid); if (Finishedstartidlist.containsall (allstartidlist)) {StRing tip = "All download complete, quantity" + finishedstartidlist.size ();
        Message msg = Handler.obtainmessage (1);
        Msg.obj = tip;
      Handler.sendmessage (msg);
      } log.i ("Demolog", "stopself (" + Startid +) ");
    Stopself (Startid);
    @Override public void OnCreate () {super.oncreate ();
  LOG.I ("Demolog", "Downloadservice-> onCreate");
    @Override public int Onstartcommand (Intent Intent, int flags, int startid) {allstartidlist.add (Startid);
    String name = Intent.getstringextra ("name");
    String url = intent.getstringextra ("url");
    LOG.I ("Demolog", "Downloadservice-> Onstartcommand, Startid:" + Startid + ", Name:" + name);
    Downloadthread downloadthread = new Downloadthread (startid, name, URL);
    Downloadthread.start ();
  return start_redeliver_intent;
  @Override public IBinder onbind (Intent Intent) {return null;
    @Override public void OnDestroy () {Super.ondestroy (); LOG.I ("Demolog", "DownLoadservice-> OnDestroy ");
 }
}

The

Downloadactivity code is as follows:

Package Com.ispring.startservicedemo;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.View;

Import Android.widget.Button;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;


Import Java.util.Map; public class Downloadactivity extends activity implements Button.onclicklistener {@Override protected void onCreate (
    Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_download);
    @Override public void OnClick (View v) {list<string> List = new arraylist<> ();
    List.add ("Overview of StartService basic usage in Android; http://www.jb51.net/article/76470.htm");

    List.add ("Android Landing interface to achieve clear input box content and vibration effect; http://www.jb51.net/article/76328.htm");

    Iterator iterator = List.iterator ();
      while (Iterator.hasnext ()) {String str = (String) iterator.next ();
      String[] splits = Str.split (";"); String name = SPLits[0];
      String URL = splits[1];
      Intent Intent = new Intent (this, downloadservice.class);
      Intent.putextra ("name", name);
      Intent.putextra ("url", url);
    StartService (Intent);

 }
  }
}

When we click the button "bulk Download article", we call the activity's StartService method many times, in which we store the article name name and the address URL of the article in its parameter intent, because we call the StartService method several times, So will download the article in bulk.

When you click the button, the console runs the following results:

After the StartService is invoked, the Android framework receives intent information, first creating an instance of Downloadservice, and then executing its OnCreate callback method. OnCreate will only be invoked once in the life cycle of the service.

When the OnCreate method is invoked, Android automatically recalls its Onstartcommand method, which in fact triggers the Onstartcommand callback method every time the startservice of the context is invoked. So Onstartcommand may be called multiple times during the service life cycle. In the Onstartcommand method we can get intent and startid,intent, the parameters that we passed in when we called the StartService method, and Startid was automatically allocated by Android, Each call to StartService will automatically get a startid, a startid means a job, which means a download task. We have two fields in the Downloadservice allstartidlist and Finishedstartidlist. Allstartidlist Store All the Startid, we put the startid we got in the onstartcommand at the beginning to store in the Allstartidlist, Then we read the article name and article address URL based on intent and create a new thread downloadthread based on this information, which is used to perform the actual network request download work. It should be noted that for the sake of code simplification we intent a new thread (Downloadthread) as soon as we get the Onstartcommand, but in the actual production environment such overhead is relatively large (thread new, thread destroy), Use the thread pool as much as possible to save overhead.

After the Downloadthread start method is executed, the Run method of the Downloadthread thread is executed, in which we execute the network request, get the input stream of the blog post, and when we get the input stream, we think the download is complete. At this point we can write it to the memory card as a file, or read it out of the app, where we do not have any processing of the input stream, we think the download is complete. When the download is complete, we deposit the Startid into the finishedstartidlist, finishedstartidlist store all the Startid of the completed job. When Finishedstartidlist has included all of the Allstartidlist's Startid, all of our download tasks are complete, and we will handler let the main thread show toast tell the user that the download is complete. At the end of the Run method we execute the stopself (Startid) method of the service. Note that we passed the Startid in the Stopself method, which means that we don't stop the service directly, we just stop the execution of the startid corresponding job, and if all the Startid job stops, The entire service is stopped and the OnDestroy callback method that executes the service is triggered when the service is stopped.

This article simply demonstrates the use of the service basic process through StartService and stopself (Startid) through a simple example of bulk download Bowen, and the code is not optimized, hoping to help you learn the service.

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.