Android cross-process communication IPC mechanism

In the Android system, applications cannot share memory, and the Android SDK provides 4 methods for cross-process communication. These 4 ways correspond exactly to 4 kinds of application components in the android system: Activity, Content Provider, Broadcast and Service.

1. The Activity can call the Activity of other applications across processes.
2. The Content Provider can access the data in other applications (returned in the form of Cursor objects) across processes. Of course, it can also add or delete the data of other applications. , Change operation
3. Broadcast can send broadcasts to all applications in the android system, and applications that require cross-process communication can monitor these broadcasts, using a passive receiving method, the client can only receive broadcast data, and cannot send to A broadcast program sends information.
4. Service is similar to Content Provider, and can also access data in other applications. Content Provider returns Cursor objects, while Service returns Java objects. This kind of service that can communicate across processes is called AIDL service. AIDL Service can An interface in the program is public, so that other application programs can access the AIDL service object like accessing the local object.

These four cross-process communication methods can be applied in different occasions. For example, you can use Activity when you need to display a visual interface, and you can use ContentProvider when you need to return a recordset.

Method 1: Access the Activity of other applications

Activity can be accessed both within the process (the same application) and across processes. If you want to access the Activity in the same application, you need to specify the Context object and the Class object of the Activity. The code is as follows:

Intent intent = new Intent(this , Test.class );
startActivity(intent);
Activity's cross-process access is slightly different from intra-process access. Although they all require Intent objects, cross-process access does not need to specify the Context object and the Class object of the Activity, but needs to specify the Action (a string) corresponding to the Activity to be accessed. Some activities also need to specify a Uri (specified by the second parameter of the Intent construction method).

In the android system, many applications provide activities that can be accessed across processes. For example, the following code can directly call the activity that makes a phone call.

Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(“tel:12345678” );
startActivity(callIntent);
After executing the above code, the system will automatically dial.

Method 2: Content Provider

  Android应用程序可以使用文件或SqlLite数据库来存储数据。Content Provider提供了一种在多个应用程序之间数据共享的方式(跨进程共享数据)。应用程序可以利用Content Provider完成下面的工作
  1. Query data
  2. change the data
  3. adding data
  4. delete data

Although the Content Provider can also be accessed in the same application, it does not make sense to do so. The purpose of Content Provider is to share data with other applications and allow other applications to add, delete, and modify data.
The Android system itself provides many Content Providers, such as audio, video, contact information, and so on. We can get a list of relevant information through these Content Providers. These list data will be returned as Cursor objects. Therefore, the data returned from the Content Provider is in the form of a two-dimensional table.

For programs accessing Content Provider, you need to use ContentResolver object. The object needs to be obtained using the getContentResolver method, the code is as follows:

ContentResolver cr = getContentResolver();
Like Activity, Content Provider also needs to correspond to a URI. Each Content Provider can control multiple data sets, in which case each data set will correspond to a separate URI. All URIs must start with "content://".

Method 3: Broadcast

  广播是一种被动跨进程通讯的方式。当某个程序向系统发送广播时,其他的应用程序只能被动地接收广播数据。这就象电台进行广播一样,听众只能被动地收听,而不能主动与电台进行沟通。

Sending broadcasts within an application is relatively simple. Just call the sendBroadcast method. This method requires an Intent object. The data that needs to be broadcast can be sent through the Intent object.

  • Static broadcast
    To receive broadcast, receiver must be registered in AndroidManifest.xml file. Let's write an application that receives broadcasts. First create an android project: receiver. Then write a MyReceiver class, which is a subclass of BroadcastReceiver.
  • Dynamic broadcast
    requires registration and deregistration
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction("con.screen.ACTION1");
context.registerReceiver(mBroadcastReceiver, myIntentFilter);

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
    
        }
}

Method 4: AIDL service

Service (Service) is a very important component in the android system. Service can run without application. In other words, the application only plays a role in starting the Service. Once the Service is started, even if the application is closed, the Service will still run in the background.

The Service in the android system has two main functions: running in the background and communicating across processes. Needless to say, running in the background, when the Service is started, the corresponding business code can be run in the Service object, and all this will not be noticed by the user. Inter-process communication is the subject of this section. If you want applications to communicate across processes, you need to use the AIDL service we talked about in this section. The full name of AIDL is Android Interface Definition Language, that is to say, AIDL is actually an interface definition language. After the interface is defined in this language, the Eclipse plug-in (ODT) will automatically generate the corresponding Java code interface code.

Socket

Socket is also called socket, which is divided into stream socket (TCP) and user datagram socket (UDP).
There are two main communication methods between Android and the server, one is Http communication, the other is Socket communication. The biggest difference between the two is that the http connection uses the "request-response method", that is, the connection channel is established when the request is made. When the client sends a request to the server, the server can return data to the client. The Socket communication can directly transmit data after the two parties establish a connection, and can realize the active push of information during the connection, without the need for the client to send a request to the server every time.

Socket based on TCP protocol:
the server first declares a ServerSocket object and specifies the port number, and then calls the accept() method of Serversocket to receive the data from the client. The accept() method is blocked when there is no data to receive. (Socketsocket=serversocket.accept()), once the data is received, read the received data through inputstream.
The client creates a Socket object, specifies the ip address and port number of the server (Socketsocket=newSocket("172.168.10.108", 8080);), reads the data through the inputstream, and obtains the data sent by the server (OutputStream outputstream=socket.getOutputStream() ), and finally write the data to be sent to the outputstream to perform socket data transmission of the TCP protocol.

name advantage shortcoming Applicable scene
Bundle easy to use Only data types supported by Bundle can be transferred Inter-process communication between the four major components
AIDL Support one-to-many concurrent communication and real-time communication It is complicated to use and needs to deal with thread synchronization One-to-many communication, concurrent communication, RPC requirements
Messenger Support one-to-many serial communication, easier to use than AIDL Does not support concurrency, does not support RPC, and can only transfer types supported by Bundle One-to-many communication, there is no concurrent execution scenario on the server side (that is, multi-process single-thread), no RPC requirements or no RPC requirements that need to return results
ContentProvider Constrained AIDL supports one-to-many concurrent communication, and provides a unified uri and a unified interface to facilitate communication Generally only CRUD operations are provided One-to-many communication, concurrent communication, RPC requirements
File Sharing easy to use Does not support concurrency and cannot communicate in real time No concurrency, suitable for scenarios where simple data exchange is not real-time
socket Support one-to-many concurrent communication and real-time communication complicated to use network data exchange

related reference

4 ways of cross-process communication in android
https://www.cnblogs.com/sevenyuan/archive/2013/03/22/2975122.html

Graphic and text explain the principle of Android Binder cross-process communication mechanism
https://www.cnblogs.com/xinmengwuheng/p/7070167.html

https://blog.csdn.net/afdafvdaa/article/details/124838018

Guess you like

Origin blog.csdn.net/weixin_44008788/article/details/120033178