Implementation of cross process communication (IPC) based on Android Application Development

Posted by ironmonk3y on Mon, 31 Jan 2022 06:45:11 +0100

The so-called cross process call, in Android application development, is different from the implementation of communication between two application processes.
Let's divide the two communicating application processes into client and server.
Here are two simple applications to understand how to realize cross process communication in Android application development.

The implementation of these two applications is very simple, that is, click the "set user name" button on the client to input the user name to the server, and then click the "get user name" button on the client to obtain the user name saved by the server.

Server side: a class that inherits Service and an Aidl file. (about the Aidl file, use IMyService.aidl from the previous article)
IMyService.aidl is defined as follows:
interface IMyService
{
String getName();
void setName(String name);
}
Imyservice created for Aidl, eclipse will automatically generate imyservice in the gen directory of the project Java file. At this time, you can move the java file to the src directory of the project. Then delete the imyservice.exe created in the src directory Aidl will do. (note that don't forget to add the project package name you created in the IMyService.java file code)

 inherit Service The remote service class code of class is as follows:

package com.feixun.hu.ipc.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class IpcService extends Service
{
//User name used to save client input
private String userName;
private ServiceBinder mServiceBinder;

@Override
public void onCreate() 
{
	// TODO Auto-generated method stub
	super.onCreate();
	//Create ServiceBinder object (Binder type object)
	mServiceBinder = new ServiceBinder();
}

/*Define a class of Binder type that inherits the implementation of the internal class Stub of IMyService interface and communicates with the client,
 * IMyService.Stub It's Binder type
 */
public class ServiceBinder extends IMyService.Stub
{

	@Override
	public String getName() throws RemoteException 
	{
		// TODO Auto-generated method stub
		return userName;
	}

	@Override
	public void setName(String name) throws RemoteException 
	{
		// TODO Auto-generated method stub
		userName = name;
	}
	
}

@Override
public IBinder onBind(Intent arg0) 
{
	// TODO Auto-generated method stub
	
	/*When connecting with the client, the Binder object is returned
	 * 1.If the connected client and the server belong to the same process, the mServiceBinder itself is directly returned here
	 * 2.If the connected client and the service do not belong to the same process, the proxy of the mServiceBinder object is returned
	 */
	return mServiceBinder;
}

}

AndroidManifest. The XML file code is as follows: (Note: the action – > "com. Feixun. Hu. Action. Ipc_service" added in the file corresponds to the action added by binding the service settings in the client)

<?xml version="1.0" encoding="utf-8"?>

<uses-sdk android:minSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <service android:name=".IpcService">
        <intent-filter >
            <action android:name="com.feixun.hu.action.IPC_SERVICE"/>
        </intent-filter>
    </service>
</application>

The so-called server in this paper is to create an application project, which contains a Service. Therefore, the server-side application is invisible when running.

Client: a class that inherits Activity and imyservice that is the same as the server Aidl file (this file is essential for communication between the two. You can directly copy the IMyService.java automatically generated by the server to the customer service).
The code of the visual class that inherits the Activity is as follows:

package com.feixun.hu.ipc.client;

import android.app.Activity;
import android.app.Service;
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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class IpcClient extends Activity
{

private IMyService mIMyService;

private Button setName, getName;
private TextView show;
private EditText input;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    //Get each component
    setName = (Button)findViewById(R.id.set);
    getName = (Button)findViewById(R.id.get);
    show = (TextView)findViewById(R.id.show);
    input = (EditText)findViewById(R.id.input);
    
    //Create Intent, corresponding to the Intent registered by the server
    Intent intent = new Intent();
    intent.setAction("com.feixun.hu.action.IPC_SERVICE");
    //Bind connection remote service
    bindService(intent, conn, Service.BIND_AUTO_CREATE);
    
    //Bind listening for setting button
    setName.setOnClickListener(new OnClickListener() 
    {
		
		@Override
		public void onClick(View v) 
		{
			// TODO Auto-generated method stub
			if(input.getText() != null)
			{
				try 
				{
					//Save the input information to the remote server
					mIMyService.setName(input.getText().toString());
				} 
				catch (RemoteException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	});
    
    //Get button binding listening
    getName.setOnClickListener(new OnClickListener() 
    {
		//String name = mIMyService.getName();
		@Override
		public void onClick(View v) 
		{
			// TODO Auto-generated method stub
			try {
				if(mIMyService.getName() != null)
				{
					show.setText(mIMyService.getName().toString());
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
	});
}

//The key part of realizing the binding between client and server
private ServiceConnection conn = new ServiceConnection() 
{
	//Disconnect the server
	@Override
	public void onServiceDisconnected(ComponentName name) 
	{
		// TODO Auto-generated method stub
		mIMyService = null;
	}
	//Connect server
	@Override
	public void onServiceConnected(ComponentName name, IBinder service) 
	{
		// TODO Auto-generated method stub
		/*The proxy for obtaining the mServiceBinder object returned through the onBind method of IpcService is implemented here.
		 * The parameter service is the mServiceBinder object of the remote service IpcService obtained by binding,
		 * And call imyservice The function asInterface of stub gets the proxy of the mServiceBinder object.
		 */
		mIMyService = IMyService.Stub.asInterface(service);
	}
};

@Override
protected void onDestroy() 
{
	// TODO Auto-generated method stub
	super.onDestroy();
	//Unbind
	unbindService(conn);
}

}

main. The code of the XML file is as follows:

<?xml version="1.0" encoding="utf-8"?>

   <Button 
       android:id="@+id/set"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/setName"/>
   
   <EditText 
       android:id="@+id/input"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:hint="@string/info"/>

   <Button 
       android:id="@+id/get"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/getName"/>
   
   <TextView 
       android:id="@+id/show"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       />

The so-called client in this paper is also to create an application project, which includes an Activity. By operating the visual component interface provided by the Activity, the user can save and obtain data from the remote server (that is, the Service service running in another application process).

The above two simple application examples can realize the most basic cross process communication between two applications. Of course, if necessary, we can also create remote services that transmit and process more complex data, not just the examples created in this article. For example, in the form of a class (similar to JavaBean), the data class is required to implement the Parcelable interface. (required by the data type defined by the interface defined in AIDL file)
Original address: http://blog.csdn.net/stevenhu_223/article/details/8738682

Topics: Android