android-Remote Service

Source: Internet
Author: User
Tags app service

http://blog.csdn.net/guolin_blog/article/details/9797169

http://www.jianshu.com/p/eeb2bd59853f

Converting a normal service to a remote service is simply a matter of specifying the Android:process property of the service when it is registered: remote is ready, and the code is as follows:

<service android:name= ". Aidlservice "        android:process=": Remote "></service>

The remote service allows the service to run in another process, so you can perform actions that block the process

The remote service is so easy to use, we will convert all the service into a remote service, and save the thread. In fact, remote service is not easy to use, even can be said to be more difficult. In general, if you can not use remote service, try not to use it.

Let's take a look at its drawbacks, first myservice the OnCreate () method to get rid of the thread sleep code, then rerun the program, and click the Bind Service button, you will find the program crashes! Why does clicking on the Start Service button program not crash, and clicking on the Bind service button will crash? This is due to the connection of Mainactivity and MyService in the Click event of the Bind service button, but currently MyService is already a remote service, Activity and service run in two different processes, and you can no longer use the traditional form of association, and the program crashes.

So how do you get activity to associate with a remote service? This will use Aidl for cross-process communication (IPC).

Callers and service will need to use the remote service invocation mechanism in Android if they are not in a process.
Android uses aidl to define communication interfaces between processes. The syntax of AIDL is similar to the Java interface, with the following points to note:

      1. The Aidl file must have a. aidl as the suffix name.
      2. The type of data used in the Aidl interface, except for the basic type, String, List, Map, charsequence, all other types require a guide package, even if both are within the same package. The element types in list and map must be types supported by Aidl.
      3. The interface name needs to be the same as the file name.
      4. When the parameter or return value of a method is a custom type, the custom type must implement the Parcelable interface.
      5. All non-Java base type parameters need to be prefixed with in, out, inout to indicate whether the parameter is an input parameter, an output parameter, or an input/output parameter.
      6. Access modifiers and static, final, and so on cannot be used before interfaces and methods.

AIDL implementation
1. First I set up 2 app projects, through AIDL implementation of one app calls another app service
The directory structure is as follows:
Service-provider App

App that uses Aidl to invoke service

2. Create a file in two apps Iperson.aidl note that the package name is the same
Iperson.aidl is just an interface file that is used to aidl the interaction, and Build-->rebuild will automatically create the required Java files when it is established in studio.

Iperson.aidl Code

 Package Mangues.com.aidl; Interface IPerson {  string greet (String someone);}

3. Establishment of Aidlservice in Aidl_service
The iperson.stub is a binder file that is automatically generated by iperson.aidl, you implement it, and then return out in Onbind (), just like the Android service implementation interacts with the activity.
Code:

 Public classAidlserviceextendsService {Private Static FinalString TAG = "Aidlservice"; Iperson.stub Stub=Newiperson.stub () {@Override PublicString greet (String someone)throwsremoteexception {log.i (TAG,"Greet () called"); return"Hello," +someone;  }  }; @Override Public voidonCreate () {Super. OnCreate (); LOG.I (TAG,"OnCreate () called"); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {log.i (TAG,"Onbind () Onstartcommand"); return Super. Onstartcommand (Intent, flags, Startid); } @Override Publicibinder onbind (Intent Intent) {log.i (TAG,"Onbind () called"); returnstub; } @Override Public BooleanOnunbind (Intent Intent) {log.i (TAG,"Onunbind () called"); return true; } @Override Public voidOnDestroy () {Super. OnDestroy (); LOG.I (TAG,"OnDestroy () called"); }}

Why do you write this here? Because the stub is actually a subclass of binder, the implementation of the stub can be returned directly in the Onbind () method.

Start this service in 4.aidl_service mainactivity
Simply do not write off something;

@Override   protected void onCreate (Bundle savedinstancestate) {      super. OnCreate (savedinstancestate);      Setcontentview (R.layout.activity_main);       New Intent (This, aidlservice.  Class);      StartService (startintent);  }

Register at Androidmanifest.xml

<service android:name= ". Aidlservice "               android:process=": remote >          <intent-filter>              <action android:name= " Android.intent.action.AIDLService "/>              <category android:name=" Android.intent.category.DEFAULT "/>          </intent-filter>      </service>

The role is to expose the service so that other apps can take advantage
The Android.intent.action.AIDLService field is bound to this service to obtain data.

Bind Aidl_service Service in 5.aidl_client to get data
Code:

 Public classMainactivityextendsappcompatactivity {PrivateIPerson person; PrivateServiceconnection conn =Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder service) {LOG.I ("Serviceconnection", "onserviceconnected () called"); person=IPerson.Stub.asInterface (service); String RetVal=NULL; Try{RetVal= Person.greet ("Scott"); } Catch(RemoteException e) {e.printstacktrace (); } toast.maketext (mainactivity. This, RetVal, Toast.length_short). Show (); } @Override Public voidonservicedisconnected (componentname name) {//This was called when the connection with the service had been unexpectedly disconnected,//that's, its process crashed. Because It is running in our same process and we should never see this happen.LOG.I ("Serviceconnection", "onservicedisconnected () called");    }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);      Setcontentview (R.layout.activity_main); Intent mintent=NewIntent (); Mintent.setaction ("Android.intent.action.AIDLService"); Intent eintent=NewIntent (Getexplicitintent ( This, mintent));  Bindservice (Eintent, Conn, context.bind_auto_create); }   Public StaticIntent getexplicitintent (context context, Intent implicitintent) {//Retrieve all services that can match the given intentPackagemanager pm =Context.getpackagemanager (); List<ResolveInfo> ResolveInfo = pm.queryintentservices (implicitintent, 0); //Make sure-one match was found      if(ResolveInfo = =NULL|| Resolveinfo.size ()! = 1) {          return NULL; }      //Get Component Info and create ComponentNameResolveInfo serviceinfo = resolveinfo.get (0); String PackageName=ServiceInfo.serviceInfo.packageName; String ClassName=ServiceInfo.serviceInfo.name; ComponentName Component=Newcomponentname (PackageName, className); //Create a new intent. use the old one for extras and such reuseIntent explicitintent =NewIntent (implicitintent); //Set the component to be explicitexplicitintent.setcomponent (component); returnexplicitintent; }}

As we have already learned in the previous article, if you want to associate activity with a service, you need to call the Bindservice () method and pass intent as a parameter, specifying the service to bind in the intent, the sample code is as follows:

New Intent (This, MyService.  Class);  Bindservice (bindintent, Connection, bind_auto_create);

Here, when building intent, you use Myservice.class to specify which service to bind, but when you bind the service in another application, you do not myservice the class, you must use the implicit intent.

<intent-filter>              <action android:name= "Com.example.servicetest.MyAIDLService"/>          </ Intent-filter>

This means that MyService can respond to intent with com.example.servicetest.MyAIDLService action.

android-Remote 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.