"Turn" Android Service II (Intentservice)

Source: Internet
Author: User

Original URL: http://rainbow702.iteye.com/blog/1143286

Regardless of the service, it runs by default in the main thread of the application (i.e., the UI thread). So, if your service is going to run very time-consuming or potentially blocked operations, your application will be suspended and even a ANR error will occur. To avoid this problem, you should restart a new thread in the service to do these things. There are two kinds of methods available for reference:

① restarts a thread directly in the service's Onstartcommand () method to execute, such as:

Java code
  1. @Override
  2. public int Onstartcommand (Intent Intent, int flags, int startid) {
  3. Myserviceactivity.updatelog (TAG + "----> Onstartcommand ()");
  4. New Thread (new Runnable () {
  5. @Override
  6. public Void Run () {
  7. //Here is a time-consuming operation, this is simply to let the thread sleep 1s
  8. try {
  9. Thread.Sleep (1000);
  10. } catch (Exception e) {
  11. E.printstacktrace ();
  12. }
  13. }
  14. }). Start ();
  15. return start_sticky;
  16. }

②android SDK provides us with an out-of-the-box service class to implement this function, it is intentservice, it is mainly responsible for the following aspects:

    • Creates a default worker thread this executes all intents delivered to onStartCommand() separate from your application ' s main thread.

Generates a default worker thread that is independent of the main thread to perform all intetnt that are passed to the Onstartcommand () method

    • Creates a work queue this passes one intent at a time to your onHandleIntent() implementation, so you never has to worry about multi -threading.

Generate a task queue to transfer the intent object to your Onhandleintent () method, sending only one intent object at a time, so you don't have to worry about multithreading.

    • Stops the service after all start requests has been handled, so you never has to call stopSelf() .

The service is automatically stopped after all requests (Intent) have been executed, so you do not need to call the Stopself () method to stop the service

    • Provides default implementation of that onBind() returns NULL.

Provides a default implementation of the Onbind () method, which returns null

    • Provides a default implementation of that sends the intent to the work queue and then to onStartCommand() your onHandleIntent() implementation

Provides a default implementation of the Onstartcommand () method, which transfers the intent to the work queue and then each time it takes out a transfer to the Onhandleintent () method from the work queue, in which the corresponding processing of the intent

Above, English from the official SDK, Chinese for my translation.

From the above, all you need to do is implement the Onhandleintent () method to implement what you want to do within the method. In addition, when inheriting intentservice, you must provide a parameterless constructor, and within that constructor you need to call the constructor of the parent class as follows:

Java code
    1. Public Hellointentservice () {
    2. Super ("Hellointentservice");
    3. }

Here is an example to explain:

Java code
  1. Activity's OnCreate ()
  2. @Override
  3. public void OnCreate (Bundle savedinstancestate) {
  4. super.oncreate (savedinstancestate);
  5. Setcontentview (R.layout.main);
  6. StartSer1 = (Button) Findviewbyid (r.id.startser1);
  7. StopSer1 = (Button) Findviewbyid (r.id.stopser1);
  8. StartSer2 = (Button) Findviewbyid (R.ID.STARTSER2);
  9. StopSer2 = (Button) Findviewbyid (R.ID.STOPSER2);
  10. Log = (TextView) Findviewbyid (R.id.log);
  11. LogView = (ScrollView) Findviewbyid (R.id.logview);
  12. Startser1.setonclicklistener (Btnlistener);
  13. Stopser1.setonclicklistener (Btnlistener);
  14. Startser2.setonclicklistener (Btnlistener);
  15. Stopser2.setonclicklistener (Btnlistener);
  16. Intent = New Intent (myserviceactivity. This, Intentservicedemo.  class);
  17. //Print out the ID of the main thread
  18. Long id = thread.currentthread (). GetId ();
  19. Updatelog (TAG + "----> onCreate () in thread ID:" + ID);
  20. }

Java code
  1. Service Code
  2. Package Com.archer.rainbow;
  3. Import Java.text.SimpleDateFormat;
  4. Import Java.util.Date;
  5. Import Android.app.IntentService;
  6. Import android.content.Intent;
  7. Public class Intentservicedemo extends Intentservice {
  8. private static final String TAG = "Intentservicedemo";
  9. private static final SimpleDateFormat Sdf_date_format = new SimpleDateFormat ("Yyyy/mm/dd hh:mm:ss.  SSS ");
  10. Public Intentservicedemo () {
  11. super (TAG);
  12. Myserviceactivity.updatelog (TAG + "----> constructor");
  13. }
  14. @Override
  15. public void OnCreate () {
  16. super.oncreate ();
  17. //Print out the ID of the service thread
  18. Long id = thread.currentthread (). GetId ();
  19. Myserviceactivity.updatelog (TAG + "----> onCreate () in thread ID:"
  20. + ID);
  21. }
  22. @Override
  23. public void OnDestroy () {
  24. Super.ondestroy ();
  25. Myserviceactivity.updatelog (TAG + "----> OnDestroy ()");
  26. }
  27. @Override
  28. public int Onstartcommand (Intent Intent, int flags, int startid) {
  29. Myserviceactivity.updatelog (TAG + "----> Onstartcommand ()");
  30. //Record the time when this request was sent
  31. Intent.putextra ("Time", System.currenttimemillis ());
  32. return Super.onstartcommand (intent, flags, Startid);
  33. }
  34. @Override
  35. public void Setintentredelivery (Boolean enabled) {
  36. Myserviceactivity.updatelog (TAG + "----> Setintentredelivery ()");
  37. super.setintentredelivery (enabled);
  38. }
  39. @Override
  40. protected void Onhandleintent (Intent Intent) {
  41. //Print out the ID of the thread used to process intent
  42. Long id = thread.currentthread (). GetId ();
  43. Myserviceactivity.updatelog (TAG
  44. + "----> onhandleintent () in thread ID:" + ID);
  45. Long time = Intent.getlongextra ("Time", 0);
  46. Date date = new Date (time);
  47. try {
  48. //Print out the corresponding trigger time for each request
  49. Myserviceactivity.updatelog (TAG
  50. + "----> Onhandleintent (): Download file ..." + Sdf_date_format.format (DATE));
  51. Thread.Sleep (3000);
  52. } catch (Interruptedexception e) {
  53. E.printstacktrace ();
  54. }
  55. }
  56. }

When the app starts, the interface looks like this:




As you can see from this diagram, the ID of the main thread (UI thread) is 1. Next, click the Start Service 1 button three times in a row to get the following screen:





As can be seen from this figure, Intentservicedemo's OnCreate () is still in the thread ID of 1, indicating that it was executed in the main thread and executed only once. Then, every time I click the button, it will trigger the Onstartcommand () method. Looking closely at the second and third OnCommand () method and the Onhandleintent () print out the statement, you will find that the second to third two-click button and the first click of the button time is not more than 3 seconds, they are continuously executed, which shows what? Note that when the first intent is processed (that is, onhandleintent () is running), the service can still accept the new request, but after accepting the new request it does not execute immediately, but instead puts them in the work queue and waits to be executed.

This is the simple use of intentservice. But if you want to have multiple threads in the service in parallel, you have to have another idea. For example, using the first method, multiple threads are used within the service, but in this case, you can handle the synchronization of the thread well.

"Turn" Android Service II (Intentservice)

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.