Android Summary series: Android Service

Source: Internet
Author: User

Service is one of the four basic components of Android and is often used in apps. In fact, the service this piece of knowledge is still a bit more, the following to be summarized under one by one.

Service is often referred to as "back-office service", where the term "backstage" is relative to the foreground, in particular, its own operation is not dependent on the user's visual UI interface, therefore, from the actual business needs to understand, the service scenario should have the following conditions:

1. Does not depend on the user visual UI interface (of course, this is not really absolute, such as the front service is used in conjunction with the notification interface);

2. Has a long time operation characteristics.

1.Service Androidmanifest.xml Statement

In general, you can divide the service into started service and bound service from the way the service is started. Any specific service startup type is customized by inheriting the service base class. When using the service, to be able to find this custom service, regardless of the type, you need to declare it in Androidmanifest.xml, with the syntax in the following format:

1 <Serviceandroid:enabled=["true"| "False"]2 android:exported=["true"| "False"]3 Android:icon= "drawable resource"4 android:isolatedprocess=["true"| "False"]5 Android:label= "string resource"6 Android:name= "string"7 android:permission= "string"8 android:process= "string" >9     . . .Ten </Service>

Where the android:exported attribute is described in detail on the previous blog post, android:name corresponds to the service class name, Android:permission is the permission declaration, and Android:process sets the specific process name. It is important to note that the service is able to use a single process in relation to its startup mode, which is explained below. The other properties are essentially the same as other components, and are no longer described too much.

Note: If the custom service is not declared in Androidmanifest.xml, when it is used, it will not crash and error like activity, but the service cannot be started, which makes it sometimes difficult to find out if you have forgotten the statement and can't locate the problem.

2.Started Service

The Started service is relatively straightforward and starts Service,context.stopservice via Context.startservice (Intent serviceintent) (Intent serviceintent) Stop this service. Of course, within the service, you can also pass the stopself (...) Way to stop it itself.

1) Started Service customization

The following code snippet shows a custom approach to the most basic started service:

1  Public classMyServiceextendsService {2 3      Public Static FinalString TAG = "MyService";4 5 @Override6      Publicibinder onbind (Intent Intent) {7         return NULL;8     }9 Ten @Override One      Public voidonCreate () { A         Super. OnCreate (); -LOG.W (TAG, "in OnCreate"); -     } the  - @Override -      Public intOnstartcommand (Intent Intent,intFlagsintStartid) { -LOG.W (TAG, "in Onstartcommand"); +LOG.W (TAG, "MyService:" + This); -String name = Intent.getstringextra ("name"); +LOG.W (TAG, "Name:" +name); A         returnStart_sticky; at     } -  - @Override -      Public voidOnDestroy () { -         Super. OnDestroy (); -LOG.W (TAG, "in OnDestroy"); in     } -}

Among them, Onbind (...) The function is the only abstract method in the service base class, and the subclass must override the implementation, and the return value of this function is useful for service of the bound service type, and in the started service type, this function returns null directly. OnCreate (...), Onstartcommand (...) and OnDestroy () are callback functions for the corresponding life cycle stages of the started service.

2) Started Service use

1  Public classMainactivityextendsActivity {2 3      Public Static FinalString TAG = "Mainactivity";4 5     PrivateButton startservicebtn;6     PrivateButton stopservidebtn;7     PrivateButton gobtn;8 9     PrivateIntent serviceintent;Ten  One @Override A     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); the  -STARTSERVICEBTN =(Button) Findviewbyid (r.id.start_service); -STOPSERVIDEBTN =(Button) Findviewbyid (r.id.stop_service); -GOBTN =(Button) Findviewbyid (r.id.go); +  -Startservicebtn.setonclicklistener (NewView.onclicklistener () { + @Override A              Public voidOnClick (View v) { atServiceintent =NewIntent (mainactivity. This, MyService.class); - StartService (serviceintent); -             } -         }); -  -Stopservidebtn.setonclicklistener (NewView.onclicklistener () { in @Override -              Public voidOnClick (View v) { to StopService (serviceintent); +             } -         }); the  *Gobtn.setonclicklistener (NewView.onclicklistener () { $ @OverridePanax Notoginseng              Public voidOnClick (View v) { -Intent Intent =NewIntent (mainactivity. This, Bactivity.class); the startactivity (intent); +             } A         }); the  +     } -  $ @Override $     protected voidOnDestroy () { -         Super. OnDestroy (); -LOG.W (TAG, "in OnDestroy"); the     } -}

As in the code snippet,

When the client calls StartService (Intent serviceintent), if MyService is first started, the OnCreate () callback is executed first and then Onstartcommand (Intent Intent, int flags, int startid), when the client calls StartService again (intent serviceintent), will only execute Onstartcommand (intent intent, int Flags, int startid), because the service has been created at this time without the need to perform a oncreate () callback. No matter how many times the StartService, only one stopservice () is required to terminate this service, execute the OnDestroy () function (in fact, it is well understood, because OnDestroy () and the OnCreate () callback are relative).

The following focuses on the following Onstartcommand (Intent Intent, int flags, int startid) methods.

Where the parameter flags is 0 by default and the corresponding constant is named Start_sticky_compatibility. Startid is a unique integer that represents the client execution StartService (...). The request is identified in multiple StartService (...) In the case of rendering 0,1,2 .... increment. In addition, this function has a return value of type int, and the specific optional values and meanings are as follows:

Start_not_sticky: When the service is killed by the system because of insufficient memory, the system will not attempt to recreate the service in the next time, even if the system memory is sufficiently available. Unless the client explicitly calls StartService (...) in the program again. Start this service.

Start_sticky: When the service is killed by the system because of insufficient memory, the next time in the future, when the system memory is sufficient, the system will attempt to recreate the service, once the creation succeeds, the callback Onstartcommand (... ) method, except that the intent will be null,pendingintent.

Start_redeliver_intent: The only difference with Start_sticky is that the callback Onstartcommand (...) method, the intent will be non-null and will be the last call to StartService (...). In the intent.

Start_sticky_compatibility:compatibility version of {@link #START_STICKY} does not guarantee this {@link #onStartCom Mand} 'll be called again after being killed. This value is generally not used, so be aware of the previous three scenarios.

In the above description, "when the service is killed by the system because of insufficient memory", it is important to note that the return value setting for this function is only meaningful for this situation, in other words, when the kill service process is considered, this function returns the value regardless of how it is set, At some point in the future, the service will not restart, even if the system memory is available enough.

Android Summary series: Android Service

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.