Explain how to use Intentservice in Android _android

Source: Internet
Author: User
Tags file url terminates volatile

Why do we need Intentservice?

Android Intentservice is inherited from the service class, before we discuss Intentservice, let's think about the characteristics of the service: the service callback method (OnCreate, Onstartcommand , Onbind, OnDestroy) are all running in the main thread. When we start the service through StartService, we need to write code to do the work in the Onstartcommand method of the service, but Onstartcommand is running in the main thread, If we need to do some time consuming operations such as network requests or IO here, this will block the main thread UI from being unresponsive, resulting in a ANR phenomenon. The best way to solve this problem is to create a new thread in the Onstartcommand and put the time-consuming code into this new thread to execute. You can refer to the previous article "Android through StartService file bulk Download,"This article in Onstartcommand opened a new thread as a worker thread to execute the network request, so this will not block the main thread. In this sense, creating a service with a worker thread is a common requirement (because worker threads do not block the main thread), so Android has developed an additional class--–intentservice to simplify the development of service,android with worker threads.

Characteristics of Intentservice

Intentservice has the following characteristics:

    • 1. Intentservice comes with a working thread and can consider using Intentservice when our service needs to do some work that might block the main thread.
    • 2. What we need to do is put the actual work into the Intentservice onhandleintent back to the method, and when we start intentservice through StartService (intent), eventually Android The framework recalls its Onhandleintent method and passes intent into the method so that we can do the actual work according to intent, and Onhandleintent runs in the worker threads that Intentservice holds, Rather than the main thread.
    • 3. When we start the Intentservice multiple times through StartService, this produces multiple jobs, and because Intentservice only holds one worker thread, each onhandleintent can only handle one job at a time. How to deal with more than one job,intentservice? The processing method is one-by-one, namely one one according to the sequential processing, first will intent1 into the onhandleintent, let it complete job1, then will intent2 into Onhandleintent, let it complete job2 ... So until all jobs are complete, we intentservice not be able to execute multiple jobs in parallel, only one by sequence, when all the jobs are complete intentservice destroyed, and the OnDestroy callback method is executed.

How to use Intentservice?

In the article "Android through StartService file bulk Download," we demonstrated how to bulk download articles through the service, now in this article we still want to demonstrate how to bulk download articles, It's just a intentservice to finish the job.

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.

The code is as follows:

Package Com.ispring.startservicedemo;
Import Android.app.IntentService;
Import android.content.Intent;

Import Android.util.Log;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;

Import Java.net.URL;
  public class Downloadintentservice extends Intentservice {public downloadintentservice () {Super ("Download");
 LOG.I ("Demolog", "Downloadintentservice constructor, Thread:" + thread.currentthread (). GetName ());
  @Override public void OnCreate () {super.oncreate ();
 LOG.I ("Demolog", "Downloadintentservice-> onCreate, Thread:" + thread.currentthread (). GetName ()); @Override public int Onstartcommand (Intent Intent, int flags, int startid) {log.i ("Demolog", "Downloadintentservic")
  E-> Onstartcommand, Thread: "+ thread.currentthread (). GetName () +", Startid: "+ Startid);
 Return Super.onstartcommand (Intent, flags, Startid); } @Override protected void Onhandleintent (Intent Intent) {HtTpurlconnection conn = null;
  InputStream is = null;
  String Blogurl = Intent.getstringextra ("url");
  String blogname = Intent.getstringextra ("name");
   try{//Download the specified file URL url = new URL (blogurl);
   conn = (httpurlconnection) url.openconnection ();
   IF (conn!= null) {//Where we get the input stream of the downloaded article, we can write it as a file to the memory card or///read it out of the text display in the app is = Conn.getinputstream ();
  }}catch (Malformedurlexception e) {e.printstacktrace ();
  }catch (IOException e) {e.printstacktrace ();
   }finally {if (conn!= null) {conn.disconnect ();  } log.i ("Demolog", "Downloadintentservice-> onhandleintent, Thread:" + thread.currentthread (). GetName () + "," "
 + Blogname + "" "Download Complete");
  @Override public void OnDestroy () {Super.ondestroy ();
 LOG.I ("Demolog", "Downloadintentservice-> OnDestroy, Thread:" + thread.currentthread (). GetName ());

 }
}

The code for Downloadactivity 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 (Bu
  Ndle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.activity_download);
  @Override public void OnClick (View v) {list<string> List = new arraylist<> ();
  List.add ("Android plays background music via startservice; http://www.jb51.net/article/76479.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, downloadintentservice.class); InteNt.putextra ("name", name);
   Intent.putextra ("url", url);
  Start Intentservice 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:

Through the above output, we can find that Downloadintentservice's OnCreate, Onstartcommand, OnDestroy callback methods are all run in the main thread, The onhandleintent is run in the worker thread Intentservice[download], which validates the first and second features of the intentservice we mentioned above.

Through the above output we will also find that after we have called five consecutive times StartService (intent), Onstartcommand was called five times in turn, and then executed Onhandleintent five times, which completes the job sequentially, When the last job completes, that is, after the last onhandleintent call completes, the entire intentservice is completed, the OnDestroy callback method is executed, and the Intentservice is destroyed.

Intentservice working principle and source analysis

In the above we have introduced the characteristics of intentservice and how to use it, then you may wonder how Android will dispatch these intent to the onhandleintent to complete the work, in fact, Intentservice works very simple, Convert the intent to a message and place it in the messages queue, and then let the handler to process it by taking it out in turn.

Intentservice source code is as follows:

Package Android.app;
Import android.content.Intent;
Import Android.os.Handler;
Import Android.os.HandlerThread;
Import Android.os.IBinder;
Import Android.os.Looper;

Import Android.os.Message;
 Public abstract class Intentservice extends Service {private volatile looper mservicelooper;
 private volatile Servicehandler Mservicehandler;
 Private String Mname;

 Private Boolean mredelivery;
  Private Final class Servicehandler extends Handler {public Servicehandler (Looper looper) {super (Looper); @Override public void Handlemessage (message msg) {//Onhandleintent is invoked in the worker thread to ensure that Onhandleintent does not block the main thread Onhandlei
   Ntent ((Intent) msg.obj);
   After executing onhandleintent, we need to call Stopself (Startid) to declare that a job is done//when all the jobs are done, Android will callback the OnDestroy method and destroy Intentservice
  Stopself (MSG.ARG1);
  } public Intentservice (String name) {//The name here will be used as the thread name Super ();
 Mname = name;
 The public void Setintentredelivery (Boolean enabled) {mredelivery = enabled; } @Override public void OncreAte () {super.oncreate (); Create Handlerthread, using Mname as the thread name, Handlerthread is intentservice worker thread handlerthread thread = new Handlerthread ("
  intentservice["+ Mname +"]);

  Thread.Start ();
  Mservicelooper = Thread.getlooper (); The Looper object that is bound by the created Handlerthread is passed to the Servicehandler so that the handler we create is bound together with the Handlerthread by Message Queuing Mservicehandler =
 New Servicehandler (Mservicelooper); @Override public void OnStart (Intent Intent, int startid) {//Create a Message object in this method, and Intent as the obj parameter for message,//So Messa
  GE is associated with intent. Message msg = Mservicehandler.obtainmessage ();
  MSG.ARG1 = Startid;
  Msg.obj = Intent;
 Sends a message with the associated intent information to Handler Mservicehandler.sendmessage (msg); @Override public int Onstartcommand (Intent Intent, int flags, int startid) {//intentservice overrides the Onstartcommand callback method: In
  Internal call OnStart callback method//So when we inherit intentservice, we should not overwrite the method, even if we override the method, we should also call Super.onstartcommand () OnStart (Intent, Startid); Return mredelivery?
 Start_redeliver_intent:start_not_sticky; } @OveRride public void OnDestroy () {//Handler quit method is called in the OnDestroy method, which terminates the message loop mservicelooper.quit ();
 @Override public IBinder onbind (Intent Intent) {return null;
} protected abstract void Onhandleintent (Intent Intent);

 }

I've added a lot of comments to the above code, and I'm sure you can understand how Intentservice works by looking directly at the code.

Intentservice inherits from the service class, and Intentservice overrides the OnCreate, Onstartcommand, OnStart, OnDestroy callback methods, And Intentservice also added a Onhandleintent callback method. Here we explain in turn the role of these methods in Intentservice.

onCreate: in the OnCreate callback method, Mname is used as the thread name to create a worker thread that Handlerthread,handlerthread is intentservice. Handlerthread after the Start method is executed, it is itself associated with Message Queuing and looper, and message queues begin to loop.

Onstartcommand: Intentservice overridden The Onstartcommand callback method: Calls the OnStart callback method internally.

OnStart: creates a Message object in the OnStart method and intent as the obj parameter of the message so that the message is associated with the intent. The message associated with intent information is then sent to handler through the handler SendMessage method.

onhandleintent: When in the OnStart method, the message is placed in the SendMessage associated with the handler by the method The Looper object associated with the handler takes a message from the queue and then passes it into the handler Handlemessage method. In the Handlemessage method, the original intent object is first obtained by obj of the message, which is then passed as an argument to the Onhandleintent method for execution. The Handlemessage method is run in Handlerthread, so Onhandleintent is also running in the worker thread. After Onhandleintent has been executed, we need to call Stopself (Startid) to declare that a job is complete. When all the jobs are done, Android will callback the OnDestroy method and destroy the Intentservice.

OnDestroy: When all jobs are completed, the service destroys and executes its OnDestroy callback method. In this method, a handler quit method is called, which terminates the message loop.

Summarize

Intentservice can do work in a worker thread without blocking the main thread, but Intentservice cannot handle multiple jobs in parallel, one after the other, after all the jobs have been completed, Automatically executes the OnDestroy method without having to call the Stopself () or stopself (Startid) method ourselves. Intentservice is not a mystery, just Android's encapsulation of a common development approach that makes it easier for developers to reduce development effort. Intentservice is a helper class, and if Android doesn't offer the class, we can write a similar one ourselves. Intentservice Service, similar to the handlerthread of handler.

I hope this article is helpful for us to understand Intentservice.

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.