Several ways of data transfer and sharing between Android application activity

Source: Internet
Author: User

One, message-based communication mechanism Intent---boudle, extra
In order to block the concept of process, Android uses different components [Activity, Service] to represent the communication between processes!
The core mechanism of communication between components is intent, which enables an activity or service to be opened through intent, whether the activity or service belongs to the current application or another application!
                
The intent consists of two parts:
1, purpose [action]--where to go
2, Content [Category, data]--on the road with what, differentiated data or content data

Intent Type:
1, explicit-directly specify the message destination, only suitable for communication between different components within the same process
New Intent (This,target.class)
2. Registration in implicit--androidmainifest.xml, generally used for cross-process communication
New Intent (String action)

implement-intent simple interprocess communication
The explicit intent is more simple!

How to implement implicit intent?
Defined in the Androidmanifest.xml file <activity>
Description
1. A <activity> includes:
0 or more <intent-filter>

It is mainly used as a matching criterion, and can be matched successfully by the <action>, <category>, <data> three tags jointly determined.

2. A <intent-filter> includes:
one or more <action>
0 or more <category>
Specify the classification characteristics of <activity>
eg
<category android:name= "Android.intent.category.LAUNCHER"/>
--Indicates that the <activity> is the first interface for the project to run

<category android:name= "Android.intent.category.HOME"/>
--Indicates that the <activity> can be used as launcher, that is, the system operation interface

<category android:name= "Android.intent.category.DEFAULT"/>
--Default condition

0 or one <data>
--Specifies the type of data to be carried and describes it using MIME type descriptions
eg
<data android:mimetype= "Video/mpeg"/>
Video/mpeg represents a video encoded in MPEG format,
You can also use the wildcard character video/* to represent the video file type in any format;

When querying ContentProvider, you can use the
<data android:mimetype= "Vnd.android.cursor.dir/vnd.myq.note"/>
The data on the query is multiple records
<data android:mimetype= "Vnd.android.cursor.item/vnd.myq.note"/>
The data on the query is a single record
As set above, to override the Sqliteopenhelper GetType (Uri Uri) method
eg
@Override
Public String GetType (Uri 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);
}
}

URI of the data by Scheme (protocol), Host,port,path four part: Scheme://host:port/path
<data android:scheme= "http://localhost:8080/test.jsp"/>

3, a intent corresponding to a variety of matching results of processing instructions
A intent has multiple matching processing components, how is the system handled?
Component type of the sub-response message:
1) If it is a service then these service can start and process messages.
2) If it is activity, a dialog box will pop up to let the user make a selection.

4, security issues
If the components between the different processes can communicate with each other through implicit messages, then the program is not easy to call to other programs or components of some sensitive programs in the system, so it will not be very safe?
In fact, Android has a unified, complete and lightweight security policy model in terms of security.

To put it simply: permission setting issues
We can define the permission ourselves, and then set the permission at the desired component, then the user must configure the permission if they want the component, otherwise the access fails!

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, configuration 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. Using permission
<uses-permission android:name= "Com.myq.android.permission.DATETIME_SERVICE"/>

two. IPC-based communication mechanisms
With intent, a message-based in-process or interprocess communication model, we can start a service through intent and jump to another activity through intent, Whether the service or activity above is in the current process or in another process, whether it is the current application or another application service or activity, through the message mechanism can communicate!

But one drawback of interprocess communication through the messaging mechanism is that if the interaction between our activity and service is not a simple activity to start a service operation, but rather to send some control requests at any time, It is important to ensure that the activity can be connected to the service at any time during service operation.

eg: Music Playback Program
Playback services in the background tend to run independently to make it easier to hear music when using other program interfaces. At the same time the background play service will also define a control interface, such as play, pause, fast forward and so on, any time the interface of the playback program can be connected to the playback service, and then through this set of control interface method to control it.

such as the demand only through the intent to open the service will not be satisfied! So the android seems a little cumbersome IPC mechanism appears, however its appearance only applies to activity and service communication, similar to the remote method call, like the C/S mode access, define an IPC interface by defining the Aidl interface file, The server side implements the IPC interface, and the client side invokes the local agent of the IPC interface.

Since the IPC call is synchronous, you should avoid calling in the main thread of the activity if an IPC service takes more than a few milliseconds to complete, otherwise the IPC call suspends the application causing the interface to lose its response. In this case, you should consider a single thread to handle IPC access.

Two interprocess IPC looks like a process going into another process executing code and returning with the result of execution.

The IPC mechanism encourages us to "maximize the use of existing functions and to collaborate on a complete project with IPC and programs that contain existing functions"

IPC Implementation Demo:
It's mine
Project--multiprocesstest
Package--com.myq.android.MultiProcessTest

1, aidl file, I was placed under the package,
The filename is called:
Idatetimeservice.aidl
the contents of the file are:
Package com.myq.android.MultiProcessTest;
Interface Idatetimeservice
{
String GetCurrentDateTime (in String format);
}

If configured correctly, a Java file with the same name will be generated under Gen
Simple summary:
The class stubs we need to implement
public interfaceIdatetimeserviceExtends Android.os.IInterface
{
...
public static abstract classStub
Extends Android.os.Binder
Implements Com.myq.android.MultiProcessTest.IDateTimeService
{
...
Gets the method of the instance Asinterface
public static Com.myq.android.MultiProcessTest.IDateTimeServiceAsinterface(Android.os.IBinder obj)
{
...
}
...
}
Our own business methods that need 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-side 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;
}
} ;

Description
A lot of information on the Internet does not involve the aidl of the IPC call specific instructions!
It is essentially the server side and client side both have the same Aidl file, to be located under the same package, that is, the package name drug, and then the correct access through proxy, Otherwise the client is in a different package than the server's Aidl file and will be faulted.

The AIDL model is as follows:
|<--------------------aidl---------------------->|
Client side-->proxy----------Parcel Packet--------stub<---server side
Thus proxy+parcel+stub constituted the aidl.
Simply, proxy runs in the client process, and the stub runs on the server side of the process.
When you go through the Aidl to access the server side, the client will block the proxy, after the service end processing, notify Proxy to return.

iv. Annexes and notes
1.
The attachment is the demo I used to test, I use the system is ubuntu9,android2.2 version
Basic Features:
The time of the current system can be output according to the different output formats selected by the user.
2.
Run Order:
Run server side first: multiprocesstest
Re-run Client: multiprocesstestclient

3.
Note the point:
Server and client-side aidl files must be in the same package or error
Security issue implementation, permission control--definition, configuration, use
Asynchronous processing Problem--handler

Several ways of data transfer and sharing between Android application activity

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.