The method service in the remote Call services, inter-process communication Adil Learning

Source: Internet
Author: User
Tags call back file copy stub mremote

1 when a process needs to invoke a method of another process, the process can throw the method through the Aidl file as an interface. For example, Android does not provide a way to hang up the phone, if the user wants to call this method must communicate with the telephone management of the application, call the method of hanging the phone.

2, below I would like to give an example of a demo invoke remote service method. To verify that the service can be started independently, the demo launches 2 remote services, one with activity and one service only. And they throw the same interface name, just learn the same name of the reference, found in a Java file can only import 1 of the same name of the class, if you want to call another class with the same name only reference his full path name: Package name + class name.

(1), including activity remote Service and interface: (Note: The Configuration service is required in the manifest file)

Service Package Com.example.androidservice;import Com.example.androidservice.iservicemethod.stub;import Android.app.service;import Android.content.intent;import Android.os.ibinder;import android.os.RemoteException; public class IService extends Service {@Overridepublic ibinder onbind (Intent Intent) {System.out.println ("Onbind"); return new Mybindle ();} @Overridepublic void OnCreate () {System.out.println ("onCreate"); Super.oncreate ();} Private class Mybindle extends Stub//Once the extension of the interface is modified to AIDL, it will be in the Gen file with the same name as the interface's package name, which automatically generates a Java file of the interface name, by looking at the interface, sending Now inside the automatic implementation of an internal class stub, which implements Ibundle and throws the interface public static abstract class stub extends Android.os.Binder implements Com.example.demoonlyservice.Iservicemethod, so we implement the return of the Ibundle when the class can directly inherit the stub, the method behind the call stub can return to the interface, will return to the bundle The service instantiates the interface and invokes the methods in the services through the interface.
{@Overridepublic void SayHello () throws RemoteException {//TODO auto-generated method Stub//sayhello (); //(1) The method name of the interface can not be the same as the name of the service, or overwrite the time can not be called, I began to directly invoke the discovery and overwrite the name of the same occurrence// Infinity loop
SYSTEM.OUT.PRINTLN ("Hello service!!!");                                                   (2) Once the method is defined in the interface, after generating the Aidl file, it is not possible to modify the contents of the Overwrite method, which is implemented by invoking the service Method    , you can modify the method in the service to modify the method that the interface throws. Sayhello2 ();}} public void Sayhello2 () {System.out.println ("Hello service!!!"); System.out.println ("Hello Service2!!!");}} Throw the interface package com.example.androidservice; Interface Iservicemethod {void SayHello ();}

The second service and interface that contains only services: (Note: The service is also required in the manifest file)

Package Com.example.demoonlyservice;import Com.example.demoonlyservice.iservicemethod.stub;import Android.app.service;import Android.content.intent;import Android.os.ibinder;import android.os.RemoteException; public class IService extends Service {@Overridepublic ibinder onbind (Intent Intent) {System.out.println ("Onbind"); return new Mybindle ();} @Overridepublic void OnCreate () {System.out.println ("onCreate"); Super.oncreate ();} Private class Mybindle extends stub{@Overridepublic void SayHello () throws RemoteException {//TODO auto-generated method Stub//sayhello ();//system.out.println ("Hello service!!!"); Sayhello2 ();}} public void Sayhello2 () {System.out.println ("Hello service!!!");}} Interface package Com.example.demoonlyservice; Interface Iservicemethod {void SayHello ();}

3 in this application, by clicking on 2 buttons to invoke the above 2 services, through the return of the Ibundle implementation of the interface method to invoke the service method SayHello

Package Com.example.getothermehod;import Com.example.androidservice.iservicemethod;//import Com.example.demoonlyservice.iservicemethod;import Android.support.v7.app.actionbaractivity;import Android.support.v7.app.actionbar;import Android.support.v4.app.fragment;import Android.content.ComponentName; Import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.os.remoteexception;import Android.view.layoutinflater;import Android.view.Menu; Import Android.view.menuitem;import android.view.view;import Android.view.viewgroup;import android.os.Build;public Class Mainactivity extends Actionbaractivity {private Iservicemethod is;private    Com.example.demoonlyservice.Iservicemethod Is2;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);//Intent intent=new Intent ("Onlyservice");//Bindservice (Intent, New MYCOnnect2 (), bind_auto_create); public void Startonlyservice (View v) throws interruptedexception {Intent intent=new Intent ("Onlyservice")    ; Bindservice (Intent, New Myconnect2 (), bind_auto_create);//try {//is2.sayhello ();/} catch (RemoteException e) {////T    ODO auto-generated catch Block//e.printstacktrace ();//}//Thread.Sleep (2000);        System.out.println (Is2==null);  } public void StartService (View v) {Intent intent=new Intent ("Providerservice"); Bindservice (Intent, New Myconnect (), bind_auto_create);//try {//is.sayhello ();/} catch (RemoteException e) {////TODO A Uto-generated catch Block//e.printstacktrace ()//}} class Myconnect implements Serviceconnection {@Overrid epublic void onserviceconnected (componentname name, IBinder service) {System.out.println ("fuck"); is= Iservicemethod.Stub.asInterface (service), try {Is.sayhello ();} catch (RemoteException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} @OverridepublIC void onservicedisconnected (componentname name) {//TODO auto-generated Method stub}} class Myconnect2 Implem Ents serviceconnection {@Overridepublic void onserviceconnected (componentname name, IBinder service) {System.out.print ln ("fuck"); Is2=com.example.demoonlyservice.iservicemethod.stub.asinterface (service); try {Is2.sayhello ();} catch ( RemoteException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} @Overridepublic void onservicedisconnected (componentname name) {//TODO auto-generated Method stub}}}

Here's a summary of the steps and issues to note:

1, first create a remote service, the demo created 2, and the name of the service is the same, in the manifest file registered action is different. There is a method in the service that needs to be accessed by other applications, namely SayHello.

2, the definition of an interface, the interface needs to be called, the name should not be the same as the method required by the service (see the first service in the Mybundle class implementation of the Code Interpretation Section), remove the interface and methods before the access rights, namely public,private, etc., and to the appropriate file directory to modify the interface extension to Aidl, save the Refresh project, you will find in Gen file and the interface with the package name of the directory under the same name as a Java file interface, click to find inside is we write the interface, it has a stub sub-class, It inherits the Bunle class and implements the method of our hug out interface, so in the service of Onbind () return to the Ibindl, the implementation of this class only need to inherit the stub, Using the stub's Asinstance method instance to instantiate the returned Ibindle as a thrown interface in the calling application, you can invoke the method in the service with this excuse.

Auto-generated Iservicemethod interface

/* * This file is auto-generated. Do not MODIFY. * Original file:d:\\ Graduation Design \\adt-bundle-windows-x86_64-20140321\\workspace\\demoOnlyservice\\src\\com\\example\\ Demoonlyservice\\iservicemethod.aidl */package Com.example.demoonlyservice;public Interface Iservicemethod extends android.os.iinterface{/** Local-side IPC Implementation stub class */public static abstract class stub extends Android.os . Binder implements com.example.demoonlyservice.iservicemethod{private static final java.lang.String descriptor = " Com.example.demoonlyservice.Iservicemethod ";/** Construct the stub at attach it to the interface. */public Stub () {this.attachinterface (this, descriptor);}  /** * Cast an IBinder object to an Com.example.demoonlyservice.Iservicemethod interface, * Generating a proxy if needed. */public static Com.example.demoonlyservice.Iservicemethod asinterface (Android.os.IBinder obj) {if ((Obj==null)) { return null;} Android.os.IInterface iin = obj.querylocalinterface (descriptor); if ((Iin!=null) && (iin instanceof Com.example.demoonlyservice.Iservicemethod)) {return ( Com.example.demoonlyservice.Iservicemethod) iin);} return new Com.example.demoonlyservice.Iservicemethod.Stub.Proxy (obj); @Override public Android.os.IBinder Asbinder () {return this;} @Override public boolean ontransact (int code, ANDROID.OS.PARCEL data, android.os.Parcel reply, int flags) throws ANDROID.O S.remoteexception{switch (code) {case interface_transaction:{reply.writestring (descriptor); return true;} Case Transaction_sayhello:{data.enforceinterface (descriptor); This.sayhello (); Reply.writenoexception (); return true;}} Return Super.ontransact (Code, data, reply, flags);} private static class Proxy implements Com.example.demoonlyservice.iservicemethod{private Android.os.IBinder Mremote; Proxy (Android.os.IBinder remote) {mremote = remote;} @Override public Android.os.IBinder Asbinder () {return mremote;} Public java.lang.String Getinterfacedescriptor () {return descriptor;} @Override public void SayHello () throws Android.os.RemOteexception{android.os.parcel _data = Android.os.Parcel.obtain (); Android.os.Parcel _reply = Android.os.Parcel.obtain (); try {_data.writeinterfacetoken (descriptor); Mremote.transact (Stub.transaction_ SayHello, _data, _reply, 0); _reply.readexception (); finally {_reply.recycle (); _data.recycle ();}}} static final int Transaction_sayhello = (Android.os.IBinder.FIRST_CALL_TRANSACTION + 0);} public void SayHello () throws android.os.RemoteException;}

3, write a class Mybindle inheritance stub, in the class call the method in the service to overwrite the method in the interface, in the Onbindle call back to open the service program.

4, in other applications to create a package name, note that the package name must be the same as the calling interface Aidl in the original application in the same package name, the source program in the interface of the Aidl file copy to the package, same-origin service, the application will automatically generate Aidl file corresponding package name and interface. Then call Bindservice to open the service.

5, the realization of a class myconnection, that is, the second parameter to open the service, it needs to implement the Serviceconnection interface, implement interface methods, there are methods onserviceconnected (componentname name, IBinder service), which is executed when the Ibindle is returned after the connection service succeeds, the second parameter is the return Ibinlde, which inherits the stub and instantiates the service as an interface through the stub method IService = IService.Stub.asInterface (service), the interface can be used to invoke the method in the services.

Note: When running a program, when you click the button response event StartService (view v) and Startonlyservice (View v), after binding the service, the interface is empty when invoking the remote service method with the interface, that is, it is not initialized. The results are printed in the order of the result: The callback event, onserviceconnected (componentname name, IBinder service), that is executed before the Click event is executed. I move the code that binds the service to the service that the OnCreate method binds at the start of the program, and then the method in the Click event to invoke the service through the interface is correct.

Order of Printing:

Method service in Remote Call service, interprocess communication Adil learning

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.