android--How the service is invoked by the binding service

Source: Internet
Author: User

service can be divided into two types depending on how it is started:
1, Started
started service is initiated by using the StartService (Intent Intent) method in application. Once this type of service is started, it will run indefinitely, even if the activity that started it is destroy off. To stop this type of service, call Stopself () in the service or call StopService (Intent Intent) in the application, or you can only wait for the Android system to kill it when the system resources are tight.

2, Bound

Bound service is initiated by invoking the Bindservice () method in the application. This type of service is bound together with application, and Android will detroy the service once all the application of the binding have disappeared. You can also actively invoke the Unbindservice () method to unbind the service.


Sometimes we want to know the status of the service in activity, such as a music player, the service is responsible for music playback, the activity is responsible for displaying the current song name and playback progress.

Can use broadcast, this also is a solution.

But if you can get a service instance, you can invoke some of the custom methods in service to get the service status.

The first thing to be clear is that the first type of service is powerless. Because there is no interface between activity and service, even if the service is start in activity, once start, the two are no longer related.

One, local service invocation.

If activity is in the same application as the service, the interaction between the two is part of the local service invocation.

Can be achieved through Bindservice, the following:

1, custom subclass MyService, Inherit service class
2, in the MyService class, the custom inner class Mybinder, inherits the Binder class

In the inner class, create methods based on the data that you want to interact with, so that the activity can get some of the data in the service through these methods. Or simply return a service instance through a method.

public class Mybinder extends Binder  {public  myservice getserviceinstance ()  {  return myservice.this;  }  }  
3. In the service class, new a Mybinder private member, and return a Mybinder instance in the Onbind () method.

This is done because once the service is bound, it will callback the Onbind () method and return a binder object to the activity. See the next step in detail.


4. In the activity, overwrite the onserviceconnected (componentname name, IBinder Service) method in the Serviceconnection interface,

The service parameter is the Mybinder object returned by the Onbind () method in the MyService class, and the custom method Getserviceinstance () that invokes the Mybinder object is used to obtain the service instance.

Here is a demo:

Import Android.os.bundle;import Android.os.ibinder;import Android.app.activity;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import    Android.view.menu;import Android.view.view;public class Mainactivity extends Activity {musicinterface mi;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Intent Intent = new Intent (this, musicservice.class);        Mixed call//In order to turn the service process into a service process startservice (intent);    In order to get the Middleman object Bindservice (Intent, New Musicserviceconn (), bind_auto_create); } class Musicserviceconn implements serviceconnection{@Overridepublic void onserviceconnected (componentname name, Ibin Der Service) {//TODO auto-generated method Stubmi = (musicinterface) service;} @Overridepublic void onservicedisconnected (componentname name) {//TODO auto-generated Method stub}}//Start play button    public void Play (View v) {mi.play ();    }//Pause play button public void pause (View v) {mi.pause (); }}

Import Android.app.service;import android.content.intent;import Android.os.binder;import android.os.IBinder;public Class Musicservice extends service{@Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stubretur N New Musiccontroller ();} Binder must be inherited in order to return the class Musiccontroller extends binder implements Musicinterface{public void Play () as a man-in-the-middle object { MusicService.this.play ();} public void Pause () {MusicService.this.pause ();}} public void Play () {System.out.println ("play Music"); public void Pause () {System.out.println ("pause playback");}}
public interface Musicinterface {void play (); void pause ();}

Second, cross-process service invocation

A cross-process service call, in the current application, invokes a service in another application.

Because Android, each application runs in its own process, has a separate instance of the Dalvik virtual machine, and is called a cross-process call (inter-process comunication).

Can be achieved through the AIDL service.

aidl (Android Interface definition Language) is a Java-like language defined by Android. Used primarily to define the interface that the server uses for data interaction with the client when cross-process calls are being invoked.

aidl service does not support all Java data types. It supports only the following types:
1, Java's simple type (int, char, Boolean, and so on). No import
2, string, and charsequence are required. No import
3, list, and map are required. No import is required (it should be noted that the element type of list and map must be aidl supported)
4, Aidl Auto-generated interface. The class that implements the Android.os.Parcelable interface requires an import
5. You need the import

to establish a simple Aidl service:
(i) server-side steps:
1, creating aidl file on server imyaidl.aidl
Aidl is similar to Java code, the sample code is as follows: (Note: The aidl file suffix is named. aidl)

Interface imyaidl{void print ();}
when the Aidl file is created, ADT automatically calls the Aidl command to generate the appropriate Java file. You can see if there is a file named Imyaidl.java under the Gen folder. If not, the. aidl file is incorrectly described.

2, inherit the service class, in the subclass, expose the Aidl interface.
This step is similar to a local service call, and returns a IBinder object through the Onbind (Intent Intent) method.
The sample code is as follows:

public class MyService extends Service{private Aidlbinder Mbinder;//stub class is a class in the Java code generated by the Aidl command in the previous step// The class implements the IBinder interface and the Imyaidl interface//can inherit the class and then return the Aidlbinder object in the Onbind () method//So that the methods defined in the Aidlbinder file are called by the Aidl object to public Class Aidlbinder extends stub{@Overridepublic void print () {System.out.println ("Hello world!") Implement the interface function in the Aidl file}} @Overridepublic void OnCreate () {mbinder = new Aidlbinder ();//Create Binder object when service is started} @Overridepublic IBinder Onbind (Intent Intent) {return mbinder;//returns Binder object for client to obtain binder object}}
3. Configuring the Androidmanifest.xml file

<!--Customize the permissions required to access the service--><permission android:protectlevel= "normal" android:name= "thomas.permission.AIDL_ SERVICE "/><service android:name=" Com.thomas.aidlserver.MyService "android:exported=" true "Android: permission= "Thomas.permission.AIDL_SERVICE" ><!--Intentfilter properties are essential--><!--so that The client can remotely invoke service--><intent-filter><action android:name= "on the server through this action" Com.thomas.aidlserver.action.AIDL_SERVICE "/></intent-filter></service>
(ii) client steps:
1. Create a Aidl file
The client also creates the Aidl file, which is exactly the same as the server's Aidl file.
Copy the service-side aidl file. It should be noted that: the package name of the Aidl file must be consistent with the server.
If the client does not have the package, create a package and place the Aidl file under the package.

2. Call service across processes
The method that the client invokes the service across processes is similar to the method of calling service locally, also through Bindservice ().
It should be noted that after successful invocation, the onserviceconnected (componentname name, IBinder Service) method in the Serviceconnection interface gets the server side Onbind () The binder object that the method passes over. The method defined in the interface can be called by converting the object type to an interface type declared in the Aidl file.
The sample code is as follows:

Private Imyaidl Maidl;mservicecon = new Serviceconnection () {@Overridepublic void onserviceconnected (componentname name , IBinder Service) {//convert IBinder type to imyaidl type. Maidl = IMyAidl.Stub.asInterface (service);} @Overridepublic void onservicedisonnected (componentname name) {}}//Remote service binding, where the action parameter of intent is the service side in// Androidmanifest.xml file in the <service> tab under the <intent-filter> specified string bindservice (new Intent (" Com.thomas.aidlserver.action.AIDL_SERVICE "), Mservicecon, service.bind_auto_create); Maidl.print ();// Calling methods declared in the Aidl file

3. Configuring the Androidmanifest.xml file

<!--the permissions required to request access to the remote service, defined in the server-side androidmanifest.xml file--><uses-permission android:name= " Thomas.permission.AIDL_SERVICE "/>








android--How the service is invoked by the binding service

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.