An overview of the basic use of startservice and its life cycle can be found in the blog "StartService Usage and service life cycle" in Android.
This article demonstrates the use of StartService and StopService (Startid) through a simple example of downloading files in bulk.
The system interface is as follows:
The interface is very simple, just a button "bulk download article", through the activity on the button to start Downloadservice.
Downloadservice is a service for downloading blog posts on CSDN, with the following code:
PackageCom.ispring.startservicedemo;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.Handler;ImportAndroid.os.IBinder;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.widget.Toast;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.net.HttpURLConnection;ImportJava.net.MalformedURLException;ImportJava.net.URL;ImportJava.util.ArrayList;ImportJava.util.List; Public class downloadservice extends Service { //Storage of all Startid PrivateList<integer> allstartidlist =NewArraylist<> ();//Store startid that have already been downloaded PrivateList<integer> finishedstartidlist =NewArraylist<> ();PrivateHandler Handler =NewHandler () {@Override Public void Handlemessage(Message msg) {if(Msg.what = =1) {String tip = (string) msg.obj; Toast.maketext (Downloadservice. This, Tip, Toast.length_long). Show (); } } }; Class Downloadthread extends Thread {//Startid information for the corresponding intent Private intStartid =0;//The article name to download PrivateString Blogname =NULL;//Address of the article to be downloaded PrivateString Blogurl =NULL; Public Downloadthread(intStartid, 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 fileURL url =NewURL ( This. Blogurl); conn = (httpurlconnection) url.openconnection ();if(Conn! =NULL){//We get the input stream for the downloaded article here, which can be written as a file to the memory card or //Read it out text to display in appis = Conn.getinputstream (); } }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 ="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,intFlagsintStartid) {allstartidlist.add (Startid); String name = Intent.getstringextra ("Name"); String URL = Intent.getstringextra ("url"); LOG.I ("Demolog","Downloadservice, Onstartcommand, Startid:"+ Startid +", Name:"+ name); Downloadthread Downloadthread =NewDownloadthread (startid, name, URL); Downloadthread.start ();returnStart_redeliver_intent; }@Override PublicIBinderOnbind(Intent Intent) {return NULL; }@Override Public void OnDestroy() {Super. OnDestroy (); LOG.I ("Demolog","Downloadservice-OnDestroy"); }}
The code for Downloadactivity is as follows:
PackageCom.ispring.startservicedemo;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportJava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.List;ImportJava.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 =NewArraylist<> (); List.add ("Use of handler in Android; http://blog.csdn.net/iispring/article/details/47115879"); List.add ("deep source parsing handler,message,messagequeue,looper;http://blog.csdn.net/iispring/article/details/47180325 in Android "); List.add ("Update the View method rollup in the main thread UI in new Android threads; http://blog.csdn.net/iispring/article/details/47300819"); List.add ("Use and principle analysis of handlerthread in Android; http://blog.csdn.net/iispring/article/details/47320407"); List.add ("Quit method and quitsafely method of Looper in Android; http://blog.csdn.net/iispring/article/details/47622705"); 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 =NewIntent ( This, Downloadservice.class); Intent.putextra ("Name", name); Intent.putextra ("url", URL); StartService (Intent); } }}
When we click the button "bulk Download article", we will call the activity's StartService method several times, in which we store the article name name and the address URL of the article in its parameter intent, because we have called the StartService method several times, So the article will be downloaded in bulk.
When you click on the button, the console run results are as follows:
After calling StartService, the Android framework receives the intent information, first creating an instance of Downloadservice and then executing its OnCreate callback method. OnCreate is only called once during the service's life cycle.
After calling the OnCreate method, Android will automatically callback its Onstartcommand method, in fact, each call to the context StartService will trigger the Onstartcommand callback method, So Onstartcommand may be called multiple times during the service's life cycle. In the Onstartcommand method we can get intent and startid,intent, which is the parameter we passed when we called the StartService method, and Startid is automatically assigned by Android, Each call to StartService will automatically get a startid, and a startid means a job, which means a download task. We have two fields Allstartidlist and finishedstartidlist in Downloadservice. Allstartidlist stores all the Startid, and we put the startid we got into the allstartidlist at the beginning of the Onstartcommand method, We then read the article name and the article address URL according to intent and create a new thread downloadthread based on this information, which is used to perform the actual network request download work. It is important to note that for the sake of code simplification we have a new thread (Downloadthread) in Onstartcommand as long as we get intent, but in the actual production environment this is much more expensive (thread new, thread destroy), You should use the thread pool as much as possible to save overhead.
After executing the Downloadthread start method, 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 to the input stream, we think the download is complete. At this point we can write it as a file to the memory card, or we can read it out of the text displayed on the app, here we do not do any processing of the input stream, we think the download is complete. After the download is complete, we put the Startid into Finishedstartidlist, Finishedstartidlist stores all the completed job Startid. When all of Allstartidlist's Startid are already included in the finishedstartidlist, all of our download tasks are complete, and we will let the main thread show the toast by handler the user article download is complete. At the end of the Run method we will execute the service's Stopself (Startid) method. It is important to note that we passed the Startid in the Stopself method, which means that we do not stop the service directly, we just stop the execution of the startid corresponding job, if all the startid corresponding jobs are stopped, The entire service is stopped and the OnDestroy callback method that executes the service is triggered when the entire service is stopped.
This article simply demonstrates the use of the service basic usage process through StartService and stopself (Startid) through the bulk download of the blog post, and the code is not optimized to help you learn the service.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android uses StartService to implement bulk download samples