Android Check Gaps (IPC)--interprocess communication basics warm up

Source: Internet
Author: User

This article codingblock article link: http://www.cnblogs.com/codingblock/p/8479282.html

Interprocess communication in Android is a relatively difficult part, at the same time very important, for interprocess communication, bloggers will use four articles to introduce, this article for the IPC series of the opening, mainly introduces some of the IPC used in some concepts, foundations, etc. The aim is to make readers ' friends have a general grasp of some necessary knowledge before they learn the IPC. There are many ways to communicate between processes in Android, and each of the following three articles will describe the advantages and disadvantages of each of these approaches.

Inter-process Communication article series articles directory:

    • Android Check Gaps (IPC)--interprocess communication basics warm up
    • Android Check Gaps (IPC)-Bundle, file sharing, ContentProvider, messenger four inter-process communication introduction
    • Android Check Gaps (IPC)--Aidl of the process communication
    • Android Check Gaps (IPC)--Introduction and example of the socket for cross-process communication
What is IPC?

IPC (full name: inter-process communication) is an interprocess communication that refers to a number of technical live methods that transmit data or signals between at least two processes.

Note: interprocess communication is something that happens between at least two processes, and we often habitually refer to a party as a client, a side called a server, and in subsequent articles there will be multiple clients and services, and children's shoes that have not been exposed to interprocess communication may not be used at first, so pay attention here.

Why use IPC?

Each process in a computer or Android system has its own part of a separate system resource that is isolated from each other and requires interprocess communication in order to be able to access resources and work together in a different process.

What is RPC?

RPC (remote Procedure Call)-an agreement that requests a service from a remote computer program over a network without needing to know the underlying network technology. (-from Baidu Encyclopedia)

The concept of RPC is used in the later introduction of Aidl, which briefly explains the role of RPC in inter-process communication between Android, in the understanding of the blogger himself, the RPC mechanism simply means that the method in the remote process can be invoked locally without concern for its underlying implementation.

What are the different implementations of IPC in Android?
    • Bundle
    • File sharing
    • ContentProvider
    • Messager
    • Aidl
    • Socket
How to open a process

Configuring process properties in the Androidmanifest configuration of the four components

Like this:

<service    android:name=".messager.MessengerService"    android:exported="true"    android:process=":remote" />

":" What is the difference between the beginning and the ":":

The process that begins with ":" Belongs to the currently applied private process, and the other app's components cannot run with it under the same process.
A process without a ":" is a global process, and other apps can run through Shareuid and it under the same process.

The Android system assigns a UID to each app and has the same UID to share the data.
Running through Shareuid in the same process requires that two applications have the same shareuid and have the same signature to be able.

The Android system allocates a separate virtual machine for each process, and different virtual machines have different address spaces on memory allocations, which results in multiple replicas of different virtual machines accessing objects of the same class.

Using multiple processes can cause the following problems:

    1. Static variables and single-instance invalidation
    2. Thread synchronization mechanism fails
    3. Sharepreference Reliability Down
    4. Application Multiple Creation
The basic concepts involved in IPC
    • Serializable
    • Parcelable
    • Binder
Serializable

Serializing with Serializable is simple, just implement the Serializable interface, and then specify a serialversionuid for the class.

The SERIALVERSIONUID working mechanism in serializable:

    1. When serializing, the system writes the serialversionuid of the current class to the serialized file (or other mediation)
    2. When deserializing, the system detects the Serialversionuid in the file, and the comparison is consistent with the seralversionuid of the current class.
    3. Consistency means that the version of the serialized class is the same as the version of the current class and can be deserialized successfully, otherwise it would indicate an error (java.io.InvalidClassException) if some conversion occurred compared to the current class and the serialized class.
    • A static variable belongs to a class that does not belong to the object and does not participate in the serialization process
    • Member variables tagged with the transient keyword do not participate in the serialization process
Parcelable

Using Parcelable for serialization is a bit more cumbersome than serializable, which requires implementing the Parcelable interface and implementing some of the necessary methods, usually in the following form:

public class Contact implements parcelable {public int phonenumber;    public String name;    public String address;        Public contact (int phonenumber, string name, string address) {this.phonenumber = PhoneNumber;        THIS.name = name;    this.address = address;    Public contact () {} @Override public int describecontents () {return 0;        } @Override public void Writetoparcel (Parcel dest, int flags) {dest.writeint (PhoneNumber);        Dest.writestring (name);    Dest.writestring (address);        } public void Readfromparcel (Parcel Parcel) {PhoneNumber = Parcel.readint ();        Name = Parcel.readstring ();    Address = parcel.readstring (); Public final static creator<contact> Creator = new creator<contact> () {@Override public Co        Ntact Createfromparcel (Parcel source) {return new contact (source);          } @Override Public contact[] NewArray (int size) {  return new Contact[size];    }    };        Public Contact (Parcel Parcel) {PhoneNumber = Parcel.readint ();        Name = Parcel.readstring ();    Address = parcel.readstring (); }}

As long as a class implements the Parcelable interface, its objects can be serialized and passed through intent and binder.

    • The parcel inside the parcelable contains serializable data that can be freely transferred in binder.
    • Serialization functionality: Writetoparcel implementation, which is done through a series of write methods in parcel.
    • Deserialization: Creator completed, completed by a series of read methods of parcel, internally showing how to create serialized objects and arrays.
    • Content Description: describecontents: Returns 1 only if a file descriptor exists in the current object, and all remaining conditions return 0.
    • The deserialization process needs to pass the current thread's context class loader, otherwise it will not be reported that the class error was found.
The difference between serializable and parcelable:
    • Serializable is a serialized interface in Java, simple to use, but expensive, and the serialization and deserialization process requires a lot of IO operations.
    • Parcelable is an interface in Android that uses trouble, but is highly efficient and preferred.
    • Parcelable is primarily suitable for memory serialization, but it is possible to serialize the object to the device via parcelable or after serialization, but it is slightly more complex, and it is recommended to use serializable.
Use of binder and the principle of upper layer
    • Binder is a class in Android that implements the IBinder interface
    • From an IPC perspective, Binder is a way of communicating across processes
    • From the Android framework point of view, Binder is ServiceManager link to various managers (Actvitiymanager, WindowManager, etc.) and the corresponding ManagerService bridge;
    • From the Android application layer, Binder is the medium of communication between the client and the server, and when Bindservice, the server returns a Binder object that contains the service-side business call.

Some methods of automatically generated binder interface classes in Aidl:

    1. Unique identifier of the Descriptor:binder, generally with the class name
    2. Asinterface (IBinder obj): An object used to convert a binder object on the service side to the Aidl interface type required by the client. (If the client and server are in the same process, this method returns the stub object itself on the server, otherwise returns STUB.PROXY)
    3. Asbinder: Returns the current binder object
    4. Ontransact: Running in the binder thread pool on the server

Binder runs on a server-side process, and if the server process is terminated abnormally, the binder link will break, causing our remote call to fail. But at this point we do not know that the binder link has been interrupted, in order to solve this problem, Binder provides two pairs of methods:

    • Linktodeath: It allows you to set up a death agent for binder and we'll get a notification when binder dies.
How to set binder Death agent:

A Deathrecipeint object is declared first and then bound to the binder by the Binder.linktodeath () method. Within the Deathrecipeint there is a method binderdied, when the binder dies, the system will callback the Binderdied method.

The sample code is as follows:

Private Serviceconnection serviceconnection = new Serviceconnection () {@Override public void Onserviceconnec            Ted (componentname name, IBinder service) {Micontactsmanager = IContactsManager.Stub.asInterface (service);            LOG.I (TAG, "onserviceconnected:micontactsmanager=" + Micontactsmanager);            try {//Set death agent Service.linktodeath for service (mdeathrecipient, 0);            } catch (RemoteException e) {e.printstacktrace (); }        }        ...}; Private Ibinder.deathrecipient mdeathrecipient = new Ibinder.deathrecipient () {@Override public void binder            Died () {///When Binder is hung, this method is executed if (Micontactsmanager = = null) {return;            }//First remove the previously bound Death Agent Micontactsmanager.asbinder (). Unlinktodeath (mdeathrecipient, 0);            Micontactsmanager = null; Then rebind the remote service Bindservice (intent, serviceconnection,Bind_auto_create); }};

The basics of interprocess communication are introduced here, and the next step will be to provide a detailed introduction to each of the interprocess communication methods.

Finally want to say is, this series for Bo master on Android knowledge again comb, check the learning process, on the one hand is forgetting things to review again, on the other hand believe in the process of re-learning will have a huge new harvest, if you also have with me the same idea, may wish to pay attention to my study together , explore each other and make progress together!

Reference documents:

    • Explore the art of Android development
Source Address: This series of the corresponding source has been synchronized to GitHub, interested students can download view, combined with code to see the article will be better. Source Portal

This article codingblock article link: http://www.cnblogs.com/codingblock/p/8479282.html

Android Check Gaps (IPC)--interprocess communication basics warm up

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.