Android service details

Source: Internet
Author: User

Service

Services in Android and windows are similar. services generally do not have user operation interfaces. They run in a system and are not easily noticed by users. You can use them to develop programs such as monitoring. Service development is relatively simple, as follows:
Step 1: Inherit the service class
Public class smsservice extends Service {}

Step 2: configure the service on the <Application> node in the androidmanifest. xml file:
<Service android: Name = ". smsservice"/>

The service cannot run on its own. You must call the context. startservice () or context. bindservice () method to start the service. Both methods can start the service, but their usage is different. The startservice () method is used to enable the service. There is no relation between the visitor and the service. Even if the visitor exits, the Service continues to run. The bindservice () method is used to enable the Service. When a visitor is bound to the service, the service is terminated once the visitor exits. This feature features that the visitor does not want to live at the same time and must die at the same time.

Start the service using the context. startservice () method. You can only call the context. stopservice () method to end the service. The ondestroy () method is called when the service ends.

Differences between the two methods to start the service:

Start and close the service through startservice () and stopservice. It is applicable to the absence of interaction between services and visitors. If a method call or passing a parameter is required between the service and the visitor, use the bindservice () and unbindservice () Methods to start and close the service.

Use context. the bindservice () method starts the service. when the service is not created, the system first calls the oncreate () method of the service and then calls the onbind () method. At this time, the visitor and the service are bound together. If the visitor wants to communicate with the service, the onbind () method must return the ibinder object. If the visitor exits, the system first calls the onunbind () method of the service and then calls the ondestroy () method. If the service has been bound before the bindservice () method is called, multiple calls to the bindservice () method will not result in multiple service creation and binding (that is, oncreate () and onbind () method is not called multiple times ). If a visitor wants to unbind from the service being bound, the unbindservice () method can be called. Calling this method also causes the system to call the onunbind () --> ondestroy () method of the service.

Service lifecycle callback Method
:

The service life cycle is related to the method used to start the service:
When the context. startservice () method is used to start the service, the related lifecycle Method
Oncreate () --> onstart () --> ondestroy ()
Oncreate () This method is called when a service is created. This method is called only once. No matter how many times the startservice () or bindservice () method is called, the service is created only once.
Onstart () calls back this method only when the context. startservice () method is used to start the service. This method is called when the service starts running. Although the startservice () method is called multiple times, the onstart () method is called multiple times.
Ondestroy () is called when the service is terminated.

When the context. bindservice () method is used to start the service, the related lifecycle Method
Oncreate () --> onbind () --> onunbind () --> ondestroy ()
Onbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller binds to the service. When the caller and the service are already bound, multiple calls to the context. bindservice () method will not cause this method to be called multiple times.
Onunbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller and the service are unbound.

If you use the startservice () method to start the service, then call the bindservice () method to bind to the service, then call the unbindservice () method to unbind, and finally call the bindservice () method to bind to the service again, the method for triggering the lifecycle is as follows:
Oncreate () --> onstart () --> onbind () --> onunbind () [true must be returned for the overloaded Method --> onrebind ()

Process Communication Using aidl and remote services

In Android, each application has its own process. How can it be implemented when objects need to be transferred between different processes? Obviously, Java does not support cross-Process Memory Sharing. Therefore, to transfer objects, You need to parse the objects into data formats that the operating system can understand to achieve cross-border object access. In Java EE, RMI is used to pass objects through serialization. In Android, aidl (Android Interface Definition Language: Interface Definition Language) is used.

Aidl is an interface definition language used to constrain communication rules between two processes for the compiler to generate code and implement inter-process communication (IPC) between two processes on the Android device ). The IPC Mechanism of aidl is similar to the CORBA used by EJB. communication information between processes is first converted to aidl protocol messages and then sent to the other party, after receiving the aidl protocol message, the recipient switches to the corresponding object. Because the communication information between processes requires bidirectional conversion, Android uses the proxy class to implement bidirectional conversion of information behind the scenes. The proxy class is generated by the android compiler and transparent to developers.

Process Communication generally takes the following four steps:

Assume that application a needs to communicate with application B and call the download (string path) method in application B. Application B provides services to application a in service mode. The following four steps are required:

1> Create * in application B *. the definition of the aidl file is similar to that of the interface, for example, in CN. itcast. create idownloadservice under the aidl package. the aidl file contains the following content:
Package CN. itcast. aidl;
Interface idownloadservice {
Void download (string path );
}
After the aidl file is created, eclipse automatically generates the idownloadservice. Java interface file in the project's Gen directory. The interface file generates a stub abstract class, which includes methods defined by aidl and other auxiliary methods. It is worth noting that asinterface (ibinder), which returns an interface-type instance. For remote service calls, the object that the remote service returns to the client is a proxy object, and the client is in onserviceconnected (componentname, when this object is referenced by the ibinder Service) method, it cannot be directly converted to an interface-type instance.
Ibinder) for type conversion.

When writing aidl files, pay attention to the following points:
1. The interface name and aidl file name are the same.
2. You do not need to add access permission modifiers such as public, private, and protected before interfaces and methods, or use final or static.
3. The types of packages supported by aidl by default are Java basic types (INT, long, Boolean, etc.) and (string, list, map, and charsequence). Import Declaration is not required when these types are used. Element Types in list and map must be supported by aidl. If you use a custom type as a parameter or return value, the custom type must implement the parcelable interface.
4. The custom type and other Interface Types generated by aidl should be explicitly imported in the aidl description file, even if the class and the defined package are in the same package.
5. All non-Java basic type parameters in the aidl file must be marked with In, out, And inout to indicate whether the parameters are input parameters, output parameters, or input and output parameters.
6. The default mark of the original Java type is in, and cannot be any other mark.

2> implement the aidl file generation interface (in this example, idownloadservice) in application B, but it is not directly implemented, instead, it is implemented through the stub of the inherited interface (the aidl interface is implemented inside the stub abstract class) and the code that implements the interface method. The content is as follows:
Public class servicebinder extends idownloadservice. Stub {
@ Override
Public void download (string path) throws RemoteException {
Log. I ("downloadservice", PATH );
}
}

3> Create a service in application B, and return the object implementing the aidl INTERFACE IN THE onbind (intent) method of the service (in this example, servicebinder ). The content is as follows:
Public class downloadservice extends Service {
Private servicebinder = new servicebinder ();
@ Override
Public ibinder onbind (intent ){
Return servicebinder;
}
Public class servicebinder extends idownloadservice. Stub {
@ Override
Public void download (string path) throws RemoteException {
Log. I ("downloadservice", PATH );
}
}
}
Other applications can access the service by implicit intent, and the intent actions can be customized. The androidmanifest. xml configuration code is as follows:
<Service android: Name = ". downloadservice">
<Intent-filter>
<Action Android: Name = "cn. itcast. process. aidl. downloadservice"/>
</Intent-filter>
</Service>

4> copy the package of the aidl file in application B together with the aidl file to application a on the client. Eclipse automatically generates the idownloadservice FOR THE aidl file in the gen directory of application. java interface file. Next, you can implement communication with application B in application a. The Code is as follows:
Public class clientactivity extends activity {
Private idownloadservice downloadservice;

@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
This. bindservice (new intent ("cn. itcast. process. aidl. downloadservice"), this. serviceconnection, bind_auto_create); // bind to the service
}

@ Override
Protected void ondestroy (){
Super. ondestroy ();
This. unbindservice (serviceconnection); // remove the service
}

Private serviceconnection = new serviceconnection (){
@ Override
Public void onserviceconnected (componentname name, ibinder Service ){
Downloadservice = idownloadservice. stub. asinterface (service );
Try {
Downloadservice. Download ("http://www.itcast.cn ");
} Catch (RemoteException e ){
Log. E ("clientactivity", E. tostring ());
}
}
@ Override
Public void onservicedisconnected (componentname name ){
Downloadservice = NULL;
}
};
}

Passing custom parameters between processes

By default, aidl supports Java basic types (INT, long, Boolean, etc.) and (string, list, MAP, charsequence ), how can I implement a custom type?

To pass a custom type, first make the custom type support the parcelable protocol. The implementation steps are as follows:
1> the custom type must implement the parcelable interface and implement the public void writetoparcel (parcel DEST, int flags) method of the parcelable interface.
2> the custom type must contain a static member named creator. The member object must implement the parcelable. Creator interface and its method.

3> Create an aidl file to declare your custom type.

Role of the parcelable interface: an instance that implements the parcelable interface can write its own state information (the State information usually refers to the value of each member variable) into parcel, you can also restore the status from parcel. Parcel is used to complete data serialization and transmission.

Difference between parcelable interface and serailzable interface:

The serailzable interface is defined in JDK, And the parcelable interface is defined by Google in Android SDK.

Are used to achieve data serialization

Different serialization Methods

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.