Android Process Communication

Source: Internet
Author: User

Android Process Communication

I. Concepts

Android uses different components [activity, Service
] To indicate the communication between processes!
The core mechanism of inter-component communication is intent.
You can enable an activity or service through intent, whether the activity or service belongs to the current application
Or other applications!





Intent contains two parts:
1. Purpose [action]
2. content [category, data] partitioned data
Or content data

Intent type:
1. explicitly -- directly specify the Message destination, which is only suitable for communication between different components in the same process
New
Intent (this, target. Class)
2. Implicit registration in androidmainifest. XML, which is generally used for cross-process communication
New
Intent (string
Action)

II. Implementation-intent simple inter-process communication

Explicit intent is relatively simple!

How to Implement implicit intent?
In the androidmanifest. xml file
Definition
<Activity
>
Note:
1. A <activity> includes:
Zero or more <intent-filter>

It is mainly used as the matching standard. Whether the matching is successful depends on three tags: <action>, <Category>, and <DATA>.

2. A <intent-filter> includes:
One or more
<Action>


Zero or multiple <Category>

Specify the classification feature of <activity>
Eg:
<Category android
: Name = "android. Intent. Category. launcher"
/>
-- This <activity> indicates that the project is running.
First Interface

<Category
Android: Name = "android. Intent. Category. Home"
/>
-- This <activity> can be used as the launcher, that is, the system
Operation Interface

<Category
Android: Name = "android. Intent. Category. Default"
/>
-- Default

Zero or one <DATA>

--
Specifies the type of data carried, which is described using the MIME type description.
Eg:
<Data Android: mimetype = "Video/MPEG"
/>
Video/MPEG: Specifies the video whose encoding format is MPEG.
,
You can also use the wildcard "Video/*" to indicate the types of video files in any format;

You can use
<Data
Android: mimetype = "Vnd. Android. cursor. DIR/vnd. myq. Note"
/>
The queried data is composed of multiple records.
<Data
Android: mimetype = "Vnd. Android. cursor. Item/vnd. myq. Note"
/>
The queried data is a single record.
Set above
, Rewrite SQLite
GetType (URI) of openhelper
Uri) Method
Eg:
@ Override
Public String GetType (URI ){
Final int
Match = surimatcher. Match (URI );
Switch (MATCH)
{
Case Notes
:
Case live_folder_notes:
Return
"Vnd. Android. cursor. DIR/vnd. myq. Note ";

Case notes_id:
Return
"Vnd. Android. cursor. Item/vnd. myq. Note ";

Default:
Throw new
Illegalargumentexception ("invalid URI:" + URI)
;
}
}

The data URI consists of four parts: Scheme: // host: Port/path.
<Data
Android: Scheme = "http: // localhost: 8080/test. jsp
"
/>

3. Processing description of Multiple matching results corresponding to an intent
An intent has multiple matching processing components. What should the system do?
Component Types of response messages:
1) if it is a service, these services can start and process messages.
2) If it is activity, a dialog box will pop up for the user to select.

4. Security Issues
If components of different processes can communicate with each other through implicit messages, the program
Isn't it safe to easily call other programs or components of some sensitive programs in the system?
In fact, Android has a unified, complete, and lightweight security policy model in terms of security.

To put it simply, it is about permission settings.
We can define the permission by ourselves and set the permission in the required component. To create this component, you must configure the permission. Otherwise, the access will fail!

Eg:
1. Define permission
<Permission-group
Android: Name = "android. permission-group.MYQ_INFO"/>
<Permission
 
Android: Name = "com. myq. Android. Permission. datetime_service"
 
Android: permissiongroup = "android. permission-group.MYQ_INFO"
 
Android: protectionlevel = "normal"
 
/>

2. Configure permission
<Service android: Name = ". datetimeservice"
Android: Permission = "com. myq. Android. Permission. datetime_service">
 
<Intent-filter>
<Action
Android: Name = "com. myq. Android. multiprocesstest. datetimeservice_action"
/>
 
</Intent-filter>
</Service>

3. Use Permission
<Uses-Permission
Android: Name = "com. myq. Android. Permission. datetime_service"/>

Iii. IPC Mechanism

With the message-based intra-process or inter-process communication model of intent, we can enable a service through intent and jump to another one through intent.
Activity, whether the preceding service or activity is in the current process or other processes, that is, whether the current application or the service or
Activity, which can communicate with each other through the message mechanism!

However, one drawback of inter-process communication through the message mechanism is that if the interaction between our activity and service is not enabled simply by the activity
Service operations, but to send some control requests at any time, you must ensure that the activity can be connected to the service at any time during the service operation.

Eg
: Playing music
Program
The playing service in the background often runs independently, so that you can hear music when using other program interfaces. At the same time, this background playing service also defines a control interface, such as playing, pause, fast forward, and other methods. At any time, the playing program interface can be connected to the playing service, and then control it through this set of control interface methods.

The above requirement cannot be met only by enabling the service through intent! Therefore, the relatively bulky IPC Mechanism of Android emerged, but its appearance only applies
Communication between activity and service is similar to remote method call, which is like access in C/S mode. By defining the aidl interface file to define an IPC Interface
Interface, the server implements the IPC interface, and the client calls the local proxy of the IPC interface.

Since IPC calls are synchronous, if an IPC service takes more than several milliseconds
Otherwise, the IPC call will suspend the application.
This causes the interface to lose response. In
In this case, consider a single thread to process IPC access.

The IPC between two processes looks like a process entering another process to execute code
Then return with the execution result.

The IPC Mechanism encourages us to "use existing functions whenever possible"
, Using IPC and programs that contain existing functions to collaborate to complete a complete project
"

IPC implementation Demo:
My
Project
--Multiprocesstest

Package --
Com. myq. Android. multiprocesstest

1. The aidl file is stored in the package,
The file name is:

Idatetimeservice. aidl
File Content:

Package
Com. myq. Android. multiprocesstest;
Interface idatetimeservice
{
String
Getcurrentdatetime (in string format)
;
}

If the configuration is correct, a Java file with the same name will be generated under Gen.
Summary:
// Stub class we need to implement
Public
InterfaceIdatetimeservice
Extends
Android. OS. iinterface
{
...
Public static abstract class
Stub


Extends Android. OS. Binder
Implements
Com. myq. Android. multiprocesstest. idatetimeservice
{
...
// Obtain
Instance method asinterface
Public
Static com. myq. Android. multiprocesstest. idatetimeservice
Asinterface
(Android. OS. ibinder
OBJ)
{
...
}
...
}
// Our own business method, which needs to be implemented
Public
Java. Lang. StringGetcurrentdatetime
(Java. Lang. string format)
Throws
Android. OS. RemoteException;
}

2. Implement idatetimeservice. stub in Service
Eg:
Package
Com. myq. Android. multiprocesstest;
Import
Java. Text. simpledateformat;
Import java. util. date;
Import
Android. App. Service;
Import Android. content. intent;
Import
Android. OS. ibinder;
Import Android. OS. RemoteException;
Import
Android. util. log;

Public class datetimeservice extends Service
{

Public static final string datetime_service_action =
"Com. myq. Android. multiprocesstest. datetimeservice_action ";

Private
Static final string tag = "-------- datetimeservice -------"
;

Private simpledateformat SDF;

Private Final
Idatetimeservice. Stub stub = new idatetimeservice. Stub ()
{

Public
String getcurrentdatetime (string format) throws RemoteException {
Return
Getcurrentdatetimestring (format );
}
};

Private synchronized
String getcurrentdatetimestring (string format)
{
SDF = new
Simpledateformat (format );
Final string temp = SDF. Format (new date ())
;
Log. I (TAG, "getcurrentdatetimestring --" + thread. currentthread () + "--" +
Temp );
Return temp;
}

Public ibinder onbind (intent arg0)

{
Log. I (TAG, "onbind --" + thread. currentthread ());
Return
Stub;
}
}

3. client code implementation
Private serviceconnection mserviceconn =
New serviceconnection ()
{

Public void
Onserviceconnected (componentname name, ibinder Service ){
Mdatetimeservice
= Idatetimeservice. stub. asinterface (service );
}

Public void
Onservicedisconnected (componentname name ){
Mdatetimeservice = NULL
;
}
};

Note:
Many materials on the Internet
There is no specific description of aidl that involves IPC calls!
In essence, it is because both the server and client have the same aidl file. It must be located under the same package, that is, the package name and drug are the same, and then can be accessed through proxy correctly, otherwise, an error occurs when the aidl file of the client and server is in a different package.

The aidl model is as follows:
 

| <-------------------- Aidl ----------------------> |
Client --> proxy ---------- parcel data packet --------
Stub <--- Server
Thus proxy + parcel + stub constitute aidl.
However, the proxy runs in the client process, while the stub runs in the server process.
When you access the server through aidl, the client will block the proxy. After the server completes processing, the proxy will be notified to return.

Iv. Attachment and description

1,
The attachment is the demo I used for testing. The system I used is ubuntu9 and android2.2.
Basic functions:
The current system time can be output according to different output formats selected by the user.
2,
Running sequence:
First run the server: multiprocesstest
Run the client: multiprocesstestclient.

3,
Note:
The aidl file on the server and client must be in the same package; otherwise, an error occurs.
Implement security issues and control permissions-define, configure, and use
Asynchronous processing -- Handler

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.