Detailed inter-process communication Android

Inter-process communication (ipc)

IPC method calls always produce client / server mode, that is, the client component (Activity / Service) holds a server-side Service component, only the method the client take the initiative to call the server, the server can not turn calls the customer end approach, because the other end of the IPC Service can not get the client object.

binder

Binder is an interprocess communication mechanism. Andrews in the cross-process communication is through the binder. When the binding service will return a binder object, and then communicate between multiple processes through him. Binder copy data only once, after the performance of shared memory.

Binder IPC mechanisms involved in the memory map) is achieved by a mmap (, mmap () is a method of operating a memory-mapping system. Simple talk is memory-mapped area of ​​memory to map user space to kernel space. After the mapping relationship, the user can modify the responses to this memory area directly to the kernel space; otherwise modify the kernel space of this region is also react directly to the user space.

Memory mapping data can reduce the number of copies, efficient interaction between user space and kernel space. Two spaces their own changes directly reflected in the mapped area of ​​memory, which was promptly perceived each other space. Precisely because of this, memory mapping can provide support for inter-process communication.

Binder IPC is based on memory mapping (mmap) to achieve

Binder communications agency model
we have explained clearly Client, Server With Binder driver to complete the implementation mechanism of the inter-process communication, but there is a problem let us confusing. A process B process of how you want an object (object) is to achieve it? After all, they belong to different processes, A Process B can not be used directly in the process object.

Earlier we introduced the process of inter-process communication has Binder driver involvement, so data flows through the drive when the drive Binder will make data conversion layer. When you want to get A process B process object, the object will not really drive and return to the A, but returns a proxy object objectProxy looks exactly the same with the object, and the object objectProxy has exactly the same way but these methods are not B processes the ability of those methods Object object, these methods only need to drive to the request parameters. A process for the direct method invocation object and it is the same.

When the message is received A Binder drive the process, found that this was objectProxy went to check their maintenance forms, an investigation found that this object is B process proxy object. Then it will go to the notification process calls the method object of B, and B requires a process to return results to themselves. When the process is forwarded to the A drive to get the process B returns the result once communication is complete

in fact inter-process communication is to achieve data sharing. Different components of a program, also known as multiple processes in different processes, and no essential difference between the two applications. Use process attributes can achieve multi-process, but will bring a lot of trouble, mainly due to shared data will fail, there are drawbacks: the static and simple interest failure, synchronization failure, sharedprefer also become unreliable and so on.

Way multi-process communication

1. Additional information extras intent to pass through bundle, the bundle transmitted supported type, such as basic data types, or to achieve pracellable object serializeable 

/ ** and specify the package name with the package name Activity name * / 
ComponentName componentName = new new ComponentName ( "com.example.androidaidl", "com.example.androidaidl.MainActivity"); 
the Intent the Intent = new new the Intent (); 
the Intent. putExtra ( "ID", 1001); 
intent.setComponent (componentName); 
startActivity (Intent);      

2. Using a shared file, or sequence of sharedpre, but does not apply to concurrent read and write
Broadcast: Android broadcasting system is level, as long as the transfer of the Action, can receive broadcast messages from other processes, the broadcast data can be passed through the Intent.
4.scheme protocol is an in-page jump in android protocol scheme by defining its own protocol, you can easily jump pages in the app, and transfers the data, or can jump the page specified by the page H5 like.
5.ContentProvider (interprocess data sharing) and the same message, but also the underlying binder, in addition to other methods oncreate method (crud) are running bindler thread. So do not oncerate in time-consuming operation. Android itself provides a lot of ContentProvider access, such as contacts, photo albums and so on. Access ContentProvider, need Uri, need to be "content: //" at the beginning. In other applications accessed by uri (hostname):

. GetActivity the ContentResolver the Resolver = () getContentResolver (); 
/**com.mh.getdata/stock this process and to add Provider located in the Uri consistent * / 
Uri uri = Uri.parse ( "Content: //com.mh. getData / Stock "); 
the Cursor Cursor = resolver.query (URI, null, null, null, null);

General Communication

Only allow customers to access services of different applications with IPC end fashion and want to handle multi-threaded (multi-tasking) in the service, only need to use AIDL. If you do not need to perform across different application of concurrent IPC, you should create a Binder by implementing the interface; or, if you want to perform IPC, but do not need multi-threading, use the Messenger class to implement the interface. In any case, before you implement AIDL, please be sure to understand binding service.
aidl document

1. passing through Messenger ( Handler ), create a handler (message received sent by the client) in the remote service where, like Messenger to return in onbind in (Messenger.getbinder). Client service bindings, holding objects Messenger message (can bundle). Handlermessage method in the remote service will receive. He is one process, if a large number of concurrent requests with aidl, Messenger bottom is aidl

Create a Messenger in the client. Then, when the client receives onServiceConnected () callback, it sends a Message to the service, and () replyTo parameter method included in its Messenger client send.
Note: Messenger and Message is both a thing

  public void sayHello(View v) {

        if (!mBound) return;
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
           mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

2. Use direct Binder object: The disadvantage is that this approach can not be cross-process and cross-application function calls. Can only be achieved in the same process, the communication between the different components of the same in an application.

Usage: Binder inheritance, then return in service in
succession Binder returned with its object, the client will bind strongly objects turn into custom Bind

AIDL

Android interface definition language (android Interface Definition Language), the method used to access the cross-process.

public static abstract class Stub extends android.os.Binder implements com.example.aidl.AidlFunctions

2. In the interface file AIDLFunctions.aidl, we define a method show

interface AidlFunctions{
    void show();
}

3.AIDL use of a Service requires cooperation, so we have to declare a Service on the server

the extends AIDLService-Service class {public 
// Stub is automatically generated 
    AidlFunctions.Stub Binder; 

    @Override 
    public void the onCreate () { 
        // the TODO Auto-Generated Method Stub 
        super.onCreate (); 
    } 

    @Override 
    public onBind the IBinder (the Intent Intent ) { 
        // TODO Auto-Generated method, Stub 
        Binder = new new AidlFunctions.Stub () { 

            @Override 
            // here is the implementation of our declared in an interface 
            public void Show () throws RemoteException { 
                // TODO Auto-Generated Stub method, 
                System.out.println ( "-------------------- --------------------- received - "); 
            } 
        };
        return binder;
    }   
}

4. Client:

// service bindings, to use ServiceConnection 
Private ServiceConnection ServiceConnection; 
interfaces, and server // custom as 
Private AidlFunctions aidlFunctions; 

ServiceConnection ServiceConnection new new = () { 

    @Override 
    public void onServiceDisconnected (ComponentName name) { 
        the System.out. the println ( "-------------------- ServiceDisconnected ----------------------"); 
    } 

    @override 
    public void s onServiceConnected (ComponentName name, the IBinder-Service) { 
        System.out.println ( "-------------------- ServiceConnected --------- ------------- "); 
        aidlFunctions = AidlFunctions.Stub.asInterface (-Service); 
    } 
};
Intent intent = new Intent("com.example.androidaidl.AIDLService");
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
//调用show方法
try {
    aidlFunctions.show();
} catch (RemoteException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

The advantage of using multiple processes to share memory is the obvious pressure of the main process. Our application bigger and bigger, more and more memory, the number of independent components into different processes, it does not take up memory space of the primary process. Of course, there are other benefits, some applications have multiple background processes, start an invisible lightweight proprietary process, send and receive messages in the background, or do some time-consuming things, or start-up of this process, and then do the listening, etc. . There is killed to prevent the main daemon process, the guardian of mutual surveillance between processes and main process, the party was killed on the re-start it. Permanent back because they want to, especially instant messaging or social networking applications.

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160188.htm