Objective
- Service as one of the four major Android components, the application is very extensive
- This article describes one of the common uses of the service: remote service
If you are not aware of the service, it is recommended to read another article I wrote:
Android Four components: the most comprehensive analysis in service history
Directory
1. The difference between a remote service and a local service
- The biggest difference between remote services and local services is that the remote service is not in the same process as the caller (that is, the remote service is running in another process), while the local service is running in the same process as the caller
- The detailed differences between the two are as follows:
2. Usage Scenarios
Multiple applications share the same background service (remote service)
A remote service that communicates across processes with components of multiple applications (four components)
3. Specific Use
In order for the remote service to cross-process communication (IPC) with the components of multiple applications (four components), the use of aidl
- Ipc:inter-process communication, i.e. cross-process communication
- Aidl:android Interface definition Language, the Android interface definition language, is used to communicate across processes between a service and multiple application components. This enables multiple applications to share the same service functionality.
In multi-process communication, there are two process roles (in the simplest case): Server side and Client
The following are the specific use steps for the two process roles:
server-side (Service)
Step 1: Create a new definition Aidl file and declare the interface that the service needs to provide to the client
Step 2: Implement the interface methods defined in Aidl in the service subclass and define the life cycle methods (Oncreat, Onbind (), BlaBla)
Step 3: Register Services & claims as remote services in Androidmainfest.xml
clients (client)
Step 1: Copy the Aidl file from the server to the directory
Step 2: Use the Stub.asinterface interface to get the binder for the server and invoke the interface methods provided by the service as needed
Step 3: Specify the service name and package for the server by intent, bind the remote service
Next, I'll use a concrete example to describe the usage of the remote service
4. Concrete examples
- Instance Description: Remote service for client remotely calling server side
- Specific use:
4.1 Server-side (Service)
Create a new server-side project: Service-server
It will be better if you look at the demo first: Github_remoteservice_server
Step 1. Create a new Aidl file
Step 2. Define the content (method) that the service needs to communicate with the activity in the new Aidl file, and compile (make Project)
// 在新建的AIDL_Service1.aidl里声明需要与Activity进行通信的方法package scut.carson_ho.demo_service;interface AIDL_Service1 { void AIDL_Service();}//AIDL中支持以下的数据类型//1. 基本数据类型//2. String 和CharSequence//3. List 和 Map ,List和Map 对象的元素必须是AIDL支持的数据类型;//4. AIDL自动生成的接口(需要导入-import)//5. 实现android.os.Parcelable 接口的类(需要导入-import)
Step 3: Implement the interface methods defined in Aidl in the service subclass and define the life cycle methods (Oncreat, Onbind (), BlaBla)
Myservice.java
Public class myservice extends Service { //Instantiate stub class for Aidl (subclass of Binder)Aidl_service1.stub Mbinder =NewAidl_service1.stub () {//Override the method defined in the interface @Override Public void Aidl_service()throwsremoteexception {System.out.println ("Client successfully communicates with remote background through Aidl"); } };//rewriting related methods to service life cycle @Override Public void onCreate() {Super. OnCreate (); System.out.println ("Oncreat () executed."); }@Override Public int Onstartcommand(Intent Intent,intFlagsintStartid) {System.out.println ("Onstartcommand () executed.");return Super. Onstartcommand (Intent, flags, Startid); }@Override Public void OnDestroy() {Super. OnDestroy (); System.out.println ("Ondestory () executed."); }@Nullable @Override PublicIBinderOnbind(Intent Intent) {System.out.println ("Onbind () executed.");//In Onbind () returns binder of stub types that inherit from binder, very important returnMbinder; }@Override Public Boolean Onunbind(Intent Intent) {System.out.println ("Onunbind () executed.");return Super. Onunbind (Intent); }}
Step 4: Register Services & claims as remote services in Androidmainfest.xml
<service android:name=".MyService" android:process=":remote" //将本地服务设置成远程服务 android:exported="true" //设置可被其他进程调用 > //该Service可以响应带有scut.carson_ho.service_server.AIDL_Service1这个action的Intent。 //此处Intent的action必须写成“服务器端包名.aidl文件名” <intent-filter> <action android:name="scut.carson_ho.service_server.AIDL_Service1"/> </intent-filter> </service>
At this point, the server side (remote service) is complete.
4.2 Clients (client)
Project to create a new client: Service-client
It will be better if you look at the demo first: github_remoteservice_client
Step 1: Copy the package containing the Aidl file from the server to the client directory (Project/app/src/main) and compile
Note: Remember to copy intact!! Don't change anything!
Step 2: Define the "Bind service" button in the main layout file
Mainactivity.xml
<?xml version= "1.0" encoding= "Utf-8"?><Relativelayout xmlns: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:paddingbottom="@dimen/activity_vertical_margin" Android:paddingleft="@dimen/activity_horizontal_margin" Android:paddingright="@dimen/activity_horizontal_margin" Android:paddingtop="@dimen/activity_vertical_margin" Tools:context="Scut.carson_ho.service_client. Mainactivity "> <buttonandroid:layout_centerinparent="true"android:id="@+id/ Bind_service "android:layout_width="match_parent "android:layout_height=" Wrap_content "android:text="binding service " /> </relativelayout>
Step 3: In the Mainactivity.java
- Use the Stub.asinterface interface to obtain the binder for the server;
- Service binding is performed by specifying the server name and package of the service by intent;
- Invoke the interface methods provided by the service as needed.
Mainactivity.java
Public class mainactivity extends appcompatactivity { PrivateButton Bindservice;//define AIDL interface variables PrivateAidl_service1 Maidl_service;//Create anonymous class for Serviceconnection PrivateServiceconnection connection =NewServiceconnection () {//Override Onserviceconnected () method and Onservicedisconnected () method //Call when activity is associated with service and disassociate @Override Public void onservicedisconnected(componentname name) { }//Called when activity is associated with a service @Override Public void onserviceconnected(componentname name, IBinder service) {//Use the AIDLService1.Stub.asInterface () method to get the IBinder object returned by the server side //Convert IBinder object to Maidl_service interface objectMaidl_service = AIDL_Service1.Stub.asInterface (Service);Try{//The interface method defined in the Myaidlservice.aidl file is invoked through the object to enable cross-process communicationMaidl_service.aidl_service (); }Catch(RemoteException e) {E.printstacktrace (); } } };@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Bindservice = (Button) Findviewbyid (R.id.bind_service);//Set button for binding serviceBindservice.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {//Specify the service name and package of the server by intent and bind to the remote service The //parameter is identical to the server-side action, which is "server package name. Aidl Interface file name"Intent Intent =NewIntent ("Scut.carson_ho.service_server. Aidl_service1 ");remote service cannot be bound by implicit intent only after//android5.0 //need to specify the package name through the Setpackage () methodIntent.setpackage ("Scut.carson_ho.service_server");//Bind service, incoming intent and Serviceconnection objectsBindservice (Intent, connection, context.bind_auto_create); } }); } }
4.3 Test results
From the above test results can be seen:
- The printed statements run in separate processes (see the package name in front of the statement);
- The client invokes a method of the server-side service
That is , the client and the server are communicating across processes
4.4 Demo Address
- Client: Github_remoteservice_client
- Service side: Github_remoteservice_server
5. Summary
- This article provides a comprehensive overview of the remote service in the Android component service
If you also want to know more about the service, please visit the following articles:
Android Four components: the most comprehensive analysis in service history
The most comprehensive analysis of android:service life cycle
Android: (Local, communication, foreground, remote) service use comprehensive introduction
Android: Remote service services (including Aidl & IPC Tutorials)
Android Multithreading comprehensive analysis: Intentservice usage & source code
The next step is to continue with the knowledge of Android development and to be interested in continuing to follow Carson_ho's Android development notes.
Please praise! Because your approval/encouragement is my biggest motive of writing!
related articles Read
Android Development: The most comprehensive and understandable Android screen adaptation solution
Android Development: Handler asynchronous communication mechanism full parse (contains Looper, Message Queue)
Android Development: Top tab Navigation bar implementation (Tablayout+viewpager+fragment)
Android Development: Bottom tab menu bar implementation (Fragmenttabhost+viewpager)
Android Development: JSON introduction and the most comprehensive analytic Method!
Android Development: Introduction to XML and comparison of Dom, SAX, pull parsing
Welcome to follow Carson_ho's book of Jane!
Occasionally share about the development of Android Dry goods, the pursuit of short, flat, fast , but not lack of depth .
Android: Remote service services (including Aidl & IPC Tutorials)