Android Learning (14) Service components

Source: Internet
Author: User

First, the definition

Run in the background, no pages, not visible. Priority is higher than activity, and when system memory is low, some activity is released first. Note that the service is also running in the main thread and cannot take some time-consuming actions. If you must do some time-consuming operations, start a new thread and process it in a new thread.

Second, the use:

Play music, record geographic changes, and listen to certain actions.

Third, Sevice classification:

1. Local Service: is a local service that is typically used inside the application, started by the StartService method, and stopped by the Stopservice,stopself,stopselfresult method. Another way to start a server: Bindservice,unbindservice.

2. Remote service: Between multiple apps within Android. Define the IBinder interface to expose the data.

  

Iv. Service declaration cycle:

The service declaration cycle is divided into two scenarios:

1, through the StartService way to start the service, for the left way, Oncreate-->onstartcommand-->service Running-->stopxxzxondestroy;

Features: After starting the service and the boot source is not connected, unable to get the service object.

2. Start the service by bind mode,oncreate--> onbind--> clients is bound to service and Onunbind-->ondestroy; as shown on the right

Features: Returns a Serviceconnection object to the startup source through the IBinder interface instance. The service object can be obtained by means of the Serviceconnection object's related methods.

Example:

1. Start Mode Declaration Cycle Example

Androidmanifest.xml, first register the service in the configuration file, add the service name

<android:name= "MyService1"></service>

Myservice1.java, create a service class, inherit the services abstract method, implement the Oncreate,onstartcommand,ondestroy,onbind method,

 PackageCom.example.servicedemo;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.IBinder; Public classMyService1extendsservice{@Override//Service Creation method, starting only once     Public voidonCreate () {System.out.println ("OnCreate"); Super. OnCreate (); } @Override//Service Startup Method     Public intOnstartcommand (Intent Intent,intFlagsintStartid) {System.out.println ("Startcommand"); return Super. Onstartcommand (Intent, flags, Startid); } @Override//Service Destruction Method     Public voidOnDestroy () {System.out.println ("Destroy"); Super. OnDestroy (); } @Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub        return NULL; }}

Main.xml, add two buttons StartService and StopService to the page.

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical">    <TextViewAndroid:id= "@+id/textview1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Start:" />    <ButtonAndroid:onclick= "DoClick"Android:id= "@+id/btn_start"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "StartService" />    <ButtonAndroid:onclick= "DoClick"Android:id= "@+id/btn_stop"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "StopService" /></LinearLayout>

Main.java, Backstage Code

 PackageCom.example.servicedemo;ImportAndroid.os.Bundle;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.view.Menu;ImportAndroid.view.View; Public classMainactivityextendsActivity {Intent Intent; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); }     Public voidDoClick (View v) {Switch(V.getid ()) { CaseR.id.btn_start://Create a Intent objectIntent =NewIntent (mainactivity. This, MyService1.class); //Start a serviceStartService (Intent);  Break;  CaseR.id.btn_stop://End a serviceStopService (Intent);  Break; }    }}

The OnCreate method is only called the first time, only once, unless the service object is unloaded, Onstartcommand Click once, you can repeat the click, Ondestory method Destruction method.

2, Bind mode binding

Androidmanifest.xml, registering the server object

<android:name= "Com.example.servicedemo2.MyBindService"></ Service >

Main.xml, place two buttons on the page, start and unload

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical">    <TextViewAndroid:id= "@+id/textview1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Bindservice:" />    <ButtonAndroid:onclick= "DoClick"Android:id= "@+id/btn_bindstart"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Bindservice" />    <ButtonAndroid:onclick= "DoClick"Android:id= "@+id/btn_bindstop"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Unbindservice" /></LinearLayout>

Mybindservice.java, creating a service class based on bind bindings

 PackageCom.example.servicedemo2;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.IBinder; Public classMybindserviceextendsservice{@Override//Binding Method     Publicibinder onbind (Intent Intent) {System.out.println ("Bind_onbind"); return NULL; } @Override//called when creating     Public voidonCreate () {System.out.println ("Bind_oncreate"); Super. OnCreate (); } @Override//called when destroying     Public voidOnDestroy () {System.out.println ("Bind_ondestroy"); Super. OnDestroy (); } @Override//called when unbinding     Public BooleanOnunbind (Intent Intent) {System.out.println ("Bind_onunbind"); return Super. Onunbind (Intent); }}

Main.java, background activity code

 PackageCom.example.servicedemo2;Importandroid.app.Activity;ImportAndroid.app.Service;ImportAndroid.content.ComponentName;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;ImportAndroid.view.View; Public classMainactivityextendsActivity {PrivateServiceconnection conn =Newserviceconnection () {@Override Public voidonservicedisconnected (componentname name) {} @Override Public voidonserviceconnected (componentname name, IBinder service) {}}; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); }         Public voidDoClick (View v) {Switch(V.getid ()) { Caser.id.btn_bindstart:intent Intent=NewIntent (mainactivity. This, Mybindservice.class);                Bindservice (Intent, conn,service.bind_auto_create);  Break;  CaseR.id.btn_bindstop:unbindservice (conn);  Break; }    }}

The start and end buttons cannot be clicked multiple times, must be started before releasing, 1 to 1, after starting the service, exiting the application, will also error, must first release the bound service source object

Android Learning (14) service component

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.