Android Development Art-chapter II IPC mechanisms

Source: Internet
Author: User
Tags sqlite database

2.1 Android IPC Simple Introduction

IPC means inter-process communication or cross-process communication, the thread is the minimum unit of CPU scheduling, is a limited system resources.

A process generally refers to an execution unit. Any operating system requires a corresponding IPC mechanism.

such as Windows can be done through the Clipboard pipe and mail slot, Linux on the ability to share the content semaphore through the named pipe.

The most distinctive inter-process communication in Android is Binder, and at the same time, it supports the Socket to implement communication between two terminals at random.

2.2 Multi-process mode in Android

(1) Enable multithreading mode by assigning the android:process attribute to four components. The process name of the default process is the package name.

android:process=":sunquan"android:process="cn.sunquan.com.xx"

":" refers to the current process name appended to the current package name, abbreviated way. The process whose process name begins with ":" Belongs to the currently applied private process, and other application components cannot be in the same process as the process name, and processes whose names do not begin with ":" belong to the global process. Other applications can run in the same process as shareuid.
(2) The system assigns a unique UID to each application and the ability to share data with the same UID. Two apps running through Shareuid in the same process need to have the same shareuid and sign the same. In such cases they can access each other's private data, such as data folders, component information, and so on. Whether or not they run in the same process.

Of course, assuming that they are running in the same process, in addition to sharing data folders, component information, they can share memory, or they look like two departments of an application.
(3) Android allocates a separate virtual machine for each application, or a separate virtual machine for each process. Different virtual machines have different address spaces on memory allocations, which results in multiple copies of objects on different virtual machines that have access to the same class. So the four components are executed in different processes. The main impact of a multi-process is to share the failure between them only if they need to share the data through memory.
(4) Multiple processes often cause problems such as the following:
1. Static members and Singleton modes fail completely: not in the same block of memory
2. The thread synchronization mechanism is completely invalid: Neither the lock object nor the lock global class can guarantee thread synchronization because the different process locks are not an object.


3. Sharepreference Reliability degradation: sharepreference The underlying is implemented by a read/write XML file, and concurrent writes can obviously be problematic. Sharepreference does not support two processes to perform write operations at the same time, otherwise there will be a chance of loss.


4. Application is created several times: When a component is running in a new process. The system creates a new process that allocates a separate virtual machine at the same time. Once the app restarts, a new application is created.

A component that executes in the same process belongs to the same virtual machine and the same application. Components of different processes do have separate virtual machines, application, and memory space.

Different components of the same application work in different processes, and there is no essential difference between the departments they belong to two applications.
(5) Although it is not possible to share memory directly, it is possible to interact with the data through cross-process communication. The way to achieve cross-process: pass data through Intent, share files, Sharepreference, Binder-based Messager and Aidl, and sockets.

2.3 IPC Basic Concept Introduction

(1) Serializable is a serialized interface provided by Java that provides standard serialization and deserialization operations for objects. The Parceable interface is a serialization method provided by Android.
(2) Implement the Serializable interface and declare a serialversionuid to enable serialization of an object. Serialversionuid is a long-numbered number that is used to assist in the serialization and deserialization process.

In principle, the Serialversionuid in the serialized number only has the same ability as the current serialversionuid to be deserialized properly. Serialversionuid's specific working mechanism: when serializing, the system writes the serialversionuid of the current class to the serialized file (which can also be other intermediaries), and when deserializing, the system detects the Serialversionuid in the file. See if it is consistent with the serialversionuid of the current class, such as a consistent description of the version number of the serialized class and the version number of the current class. Deserialization can be successful at this time, otherwise the current class and the serialized class have undergone some transformations, in general we should specify the Serialversionuid.
Note : 1. Static member variables belong to a class that does not belong to the object, not to the serialization process; 2. The member variable marked with the Transient keyword does not participate in the serialization process.
(3) Implement the Parceable interface, where objects of a class can be serialized and passed through Intent and binders. Pacel internal packaging of serializable data, can be freely transferred in Binder, can be directly serialized to have Intent, bundles, Bitmap, List, map and so on. The premise is that each element within them is serializable.


(4) Differences between Serializable and parceable: Serializable is a serialized interface in Java, which is simple to use but expensive due to the large number of I/O operations.

Parceable is a serialization method in Android. More suitable on Android platform, the disadvantage is the use of trouble, but high efficiency. The parceable is mainly used in memory sequences, and is applied to the storage device or after serialization to the network to establish the applicable Serializable.
(5) Binder is a class in Android. It implements the Binder interface. From an IPC perspective, Binder is a way of communicating across processes in Android. Binder can also be understood as a virtual physical device, and device drivers are/dev/binder. This communication mode is not in Linux, from the Android Framework perspective. Binder is the bridge that ServiceManager connects various managers and corresponding managerservice, and from the Android application layer, Binder is the medium of communication between client and server. When the Bindservice. The server returns a Binder object that contains the service-side business call. With this Binder object, the client is able to obtain the services or data provided by the server. The services here include General Service and AIDL based services.
Android in development. Binders are used primarily in Service. Contains Aidl and Messager. The Binder in the common Service does not involve interprocess communication. More simple.

And the bottom of messager is actually aidl.


(6) The Aidl tool automatically generates the parsing of the Java interface according to the aide file: declares several interface methods, declares several integer IDs at the same time to identify these interfaces, and the ID identifies which method the client requested during the Transact process. An internal class Stub is then declared. This Stub is a Binder class. When the client and the server are in the same process. Will not go through the process of transact process, assuming that not the same process, method calls need to go transact process, this logic has the STUB internal proxy proxies to complete.
Its core implementation is its internal class stub and stub internal proxy proxies.

Several of its methods are analyzed such as the following:
1. Asinterface (Android.os.Binder obj): An object used to convert a Binder object on the service side to the Aidl interface type required by the client.

Suppose the client and the server are in the same process. Then this method returns the Stub object itself on the service side, or returns the Stub.proxy object after the system is encapsulated.
2. Asbinder: Used to put back the current Binder object
3. Ontransact: In a Binder thread that executes on the server, when the client initiates a cross-process request, the remote request is handled by this method after the system's underlying encapsulation.

The method is prototyped as public Boolean ontranact (int code, ANDROID.OS.PARCEL data, android.os.Parcel reply, int flags). The server uses code to determine what the target method is requested by the client, and then takes the required number of parameters from the data to the target method (assuming the target method has a number of parameters). The target method is then executed. When the target method finishes executing. The return value is written to reply (assuming that the target method has a return value).

Assume that this method returns false. Then the client's request will fail and be able to do permission validation through this feature.
4. Proxy#[method]: Execute in client, when client calls this method, first create the input type Parcel object _data, Output type Parcel object _repley and return value object required by the method. Writes the parameter information for the method to _data (assuming there are parameters) and then calls the Transact method to initiate the RPC (remote Procedure Call) request, at the same time the current thread hangs. The Ontransact method of the server is then called until after the RPC process returns. The current thread resumes execution and extracts the return result of the RPC procedure from the _reply. Finally, the data in the _reply is returned.
Note: 1. When client initiates a request, the current thread is suspended until the server process returns data. Assuming that the remote method is time consuming, you cannot initiate this remote request in the UI thread. 2. The binder method of the server is executed in the binder's thread pool. Whether the Binder method is time-consuming or not, it should be implemented in a synchronous way, due to execution in a thread.
5. The essence of the Aidl file is that the system provides a high-speed tool to implement Binder. We can write them by hand. It is also possible to make the system self-generated by aidl files.
6. Binder has two very important methods: Linktodeath and Unlinktodeath. Binder execution on the server side, the service side process terminated abnormally for some reason, the service side of the binder connection broken, causing the client remote call failed. By Linktodeath, you can set up a death agent for binder, and when Binder dies, you receive a notification that you can initiate a connection request again to restore the connection.


Set Binder death Agent for example the following:
First declare a Deathrecipient object, Deathrecipient is an interface, there is only one method inside Binderdied, when Binder dies. The system callbacks this method and we are able to remove the binder agent that was bound before and bind the remote service again.

privatenew IBinder.DeathRecipient() {    @Override    publicvoidbinderDied() {        ifnullreturn;        0);        null;        // TODO:这里又一次绑定远程Service    }};

Second, after the client binds the remote service successfully. To set a death agent for Binder:

mservice= IMessageBoxManager.Stub.asInterface(binder);binder.linkToDeath0)

The second parameter of the Linktodeath is a marker bit. Set it directly to 0. In addition, by means of binder, isbinderalive can also infer whether Binder dies.

2.4 IPC Mode in Android

(1) using bunble:bunble to achieve the Parcelable interface, can be transferred between different processes.

A type that is not supported by bunble cannot be transferred between processes through it.
(2) using file sharing: Since the Android system based on Linux, concurrent read/write files can be unrestricted, two threads write to the same file is performed, but may be problematic.

File sharing is a good way to communicate between processes that require low data synchronization. and to properly handle the concurrent read/write problems.

Sharedpreference is a special case that belongs to a file. However, the system has a certain caching strategy for its read/write, that is, there will be a cache of sharedpreference files in memory, so under multi-process, the system is not reliable for its read/write, facing high concurrency read/write access. Sharedpreference have a very large chance of losing data. Therefore, it is not recommended to use sharedpreference in interprocess communication.


(3) Using Messenger:messenger is a lightweight IPC scheme whose underlying implementation is aidl, which processes a client-sent message in a serial manner, with the service side processing a request at a time. There is no case for concurrent execution (Messenger is inappropriate for a large number of concurrent requests).
(4) Using aidl: First, the server creates a service to listen to the client connection request. Create a Aidl file that declares the interface exposed to the client in this aidl file. This AIDL interface is implemented in the last Service. The client binds the Server service and establishes a connection to access the remote server's approach.
1. AIDL Supported data types: basic data types (int, long, chat, Boolean, double, etc.); String and Charsequence;list (only support ArrayList, the child elements inside must be aidl supported). Map (only supports HASHMAP. Each element inside must be supported by AIDL, containing key and value), parcelable (so the object that implements the Parcelable interface), Aidl (all AIDL interfaces can also be used in aidl files).
2. parcelable objects and Aidl files that you define are explicitly import even if they are in the same package as the current Aidl file.
3. Assuming that the Aidl file uses its own definition Parcelable object, you must create a new Aidl file with the same name and declare it as the parcelable type.
4. In addition to the basic data types in Aidl, other types of parameters must be marked with the direction: in, out, or inout. In indicates the input type parameter, out represents the output type parameter.
5. The Aidl interface only supports methods and does not support declaring static constants. Different from the traditional interface.
6. To facilitate the development of AIDL. It is recommended that all classes and files related to Aidl be placed in the same package. When the client is still there is an application. The entire package can be copied directly into the clientproject.
7. Remotecallbacklist is an interface that the system specifically provides to remove process listener, remotecallbacklist is a generic type. Support for managing arbitrary aidl interfaces, all Aidl interfaces inherit from the Interface interface, and within it there is a MAP structure dedicated to preserving all aidl callbacks. The key of its Map is the Binder type, and value is the Callback type. When the client process terminates, it is able to voluntarily remove the listener of the client's note.

In addition, remotecallbacklist internal self-initiative to achieve the function of thread synchronization, so use it for the registration and reconciliation register. No additional threads are required to work synchronously. The use of remotecallbacklist requires attention: it is not a List. Traversing remotecallbacklist needs to be done in the following manner. The Beginbroadcast and Finishbroadcast must be paired, even if only the number of elements in the remotecallbacklist is obtained:

int N =mListenerList.beginBroadcast();   fori0ii++){            //              }    mListenerList.finishBroadcast();
  1. Both the onserviceconnected and onservicedisconnected methods of the client are executed in the UI thread, so it is not possible to invoke the service-side time-consuming method directly inside them.

    The server-side approach itself executes in the Binder thread pool on the server side, so the server-side approach itself can perform a lot of time-consuming operations, and this time remember not to thread the asynchronous task in the server-side approach. Unless you understand what to do.

  2. Binder may die unexpectedly. Need to connect the service again. There are two ways: to set the Binder to deathrecipient monitoring, death will receive the Binderdied method callback, and then be able to re-connect, one is to re-connect in the onservicedisconnected. The difference: onservicedisconnected is called back in the client's UI thread. Binderdied is called back in the client's Binder thread pool and cannot access the UI.
  3. Aidl uses frequently used permissions authentication methods: One is to validate in Onbind and verify that the service cannot be bound directly by returning null,client. The authentication method, such as using permission authentication, declares the required permissions in androidmenifest (self-defined permission). This method is also applicable in Messenger. The second is to verify the permissions in the server-side Ontransact method. Suppose the validation failure returns false so that the service side does not terminate the method in Aidl to protect the service side. Verification methods can also be used permission. can also use Uid and Pid to do the verification. Use Getcallinguid and getcallingpid to get the Uid and Pid of the application that the client belongs to.

    This two-parameter can be used to do some verification work, such as verifying the package name.


    (5) Using Contentprovider:contentprovider is available in Android specifically for sharing data between different applications. Like Messenger, its underlying implementation is Binder, when in fact the process is much simpler than aidl. The data is organized primarily in tabular form and can contain multiple tables. It also supports file data, such as pictures and videos.

    The structure of the file data and tabular data is different, so processing such data can return a handle to the file in ContentProvider to the outside world so that the file can be visited by the Contentprovider,android system provides the Mediastore function is the file type ContentProvider.

    ContentProvider's underlying data looks like a SQLite database, but ContentProvider does not have any requirements for the underlying data storage. can use SQLite database, can also use ordinary files, even can adopt an object in memory for data storage. To observe the data changes in a contentprovider, you can register the observer with the Contentresolver Registercontentobserver method. The Unregistercontentobserver method can be used to remove the viewer.
    (6) The use of Socket:socket is called socket, which is divided into two types: stream socket and User datagram socket. The TCP and UDP protocols that correspond to the transport control layer of the network, respectively.

2.5 Binder Connection Pool

When the project to a certain extent, unlimited add service is not correct, service is one of the four components. is also a system resource. We need to put all the aidl in the same Service to manage. Working mechanism: Each business module creates its own Aidl interface and implements this interface, and there is no coupling between the different business modules. All implementation details are separated, and then the server side is provided with its own unique identity and its corresponding Binder object. For the service side only need a service to be able, the server provides a Querybinder interface, the interface can be based on the characteristics of the business module to return the corresponding Binder object to them. The main function of binder connection pooling is to forward the binder request of each business module to the remote service to execute, so as to avoid repeatedly creating the service, when the different business modules get the binder objects needed to make remote method calls. It is recommended to use Binderpool in development.

Specific source Code view:
Https://github.com/singwhatiwanna/android-art-res/blob/master/Chapter_2/src/com/ryg/chapter_2/binderpool/BinderPool.java

2.6 Using the appropriate IPC method

Android Development Art-chapter II IPC mechanisms

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.