Data transmission and sharing between Android Application Activities

Source: Internet
Author: User


Data transmission and sharing between Android Application Activities (1)

1. Message-based communication mechanism intent --- boudle, extra

Data types are limited, such as non-serializable bitmap, inputstream, or linklist linked lists.

2. Use static data,Public static member variable;

3. Transmission Based on external storage,File/preference/SQLite, if you want to target third-party applications, you need content provider

4. IPC-based communication mechanism

Transmission between context and service, such as communication between activity and service, defines the aidl interface file.

Example: http://www.eoeandroid.com/thread-36249-1-1.html

5. Based on application context, the example is as follows:

In the current activity, two values are passed to test. However, if you encounter non-serializable data, such as bitmap and inputstream, intent will be powerless. Therefore, we naturally think of another method, static variables. The following code is used:

Public class product extends Activity
{
Public static bitmap mbitmap;

}

For the above Code, any other class can directly use the mbitmap variable in product. This is easy and cool, but very wrong. We should never think that the garbage collector of the davlik virtual machine will help us reclaim unwanted memory garbage. In fact, recyclers are unreliable, especially on mobile phones. Therefore, unless we want to make our program worse and worse, we should try to stay away from static.

Note: static bitmap, drawable, and other variables are often used. It may throw a very famous exception in the Android system (the word "budget" has never been remembered. Since this exception is often thrown, the word has finally become quite familiar ,)

Error/androidruntime (4958): caused by: Java. Lang. outofmemoryerror: bitmap size exceeds VM budget

If you do not use static, you must have a method to replace it (although I like public static very much, I believe many people like it, but for our program, we suggest you stick to it ), this new solution is the topic of this article. This is the application context, which is equivalent to the application of a web program. its lifecycle is as long as that of an application (which I like ).

Now let's take a look at how to use this application context. You can use context. getapplicationcontext or context. getapplication to obtain the application context. Note that we only obtain the context object, and the more ideal method is to obtain the object of a class. OK, just do it. The following defines a class.

Package net. blogjava. mobile1;

Import Android. App. Application;
Import Android. Graphics. Bitmap;

Public class MyApp extends Application
{
Private bitmap mbitmap;

Public bitmap getbitmap ()
{
Return mbitmap;
}

Public void setbitmap (Bitmap bitmap)
{
This. mbitmap = bitmap;
}

}

The above class is essentially different from the ordinary class. However, this class is a subclass of application. By the way, this is the first step to use application context to define a class that inherits from the application. Then, define any variables in this class that we want to make global, such as bitmap in this example. An important step is to use the Android: Name attribute in the <Application> tag to specify this class. The Code is as follows:

<Application Android: Name = ". MyApp" Android: icon = "@ drawable/icon" Android: Label = "@ string/app_name">
 
</Application?

The next step is to save the bitmap object to the MyApp object or retrieve the bitmap object from the MyApp object. The code for storing the bitmap object is as follows:

MyApp = (MyApp) getapplication ();

Bitmap bitmap = bitmapfactory. decoderesource (this. getresources (), R. drawable. Icon );

MyApp. setbitmap (Bitmap );

Get bitmap object code:

Imageview = (imageview) findviewbyid (R. Id. ivimageview );

MyApp = (MyApp) getapplication ();

Imageview. setimagebitmap (MyApp. getbitmap ());

The above two pieces of code can be used in any service or activity. Global.

Refer:

1. http://flyvenus.net /? P = 229

2. http://blog.csdn.net/nokiaguy/archive/2010/11/10/5998986.aspx

Reprinted from: http://blog.csdn.net/kieven2008/archive/2010/11/13/6006905.aspx

 

I,Message-based communication mechanismIntent --- boudle, extra
To block the process concept, Android uses different components [activity, Service] to indicate 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. Objective [action] -- where to go
2. content [category, data]-What is included in the road, partition 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)

Implement-intent simple inter-process communication
Explicit intent is relatively simple!

How to Implement implicit intent?
Define <activity> In the androidmanifest. xml file
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 <actions>
Zero or multiple <Category> 
Specify the classification feature of <activity>
Eg:
<Category Android: Name = "android. Intent. Category. launcher"/>
-- This <activity> is the first interface for running the project.

<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 the data carried, which is described by the MIME type description.
Eg:
<Data Android: mimetype = "Video/MPEG"/>
Video/MPEG indicates 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.
In the preceding settings, you must override the GetType (URI) method of sqliteopenhelper.
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, isn't the program easy to 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"/>

Ii. IPC-based communication 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 activity through intent, whether the above service or activity is in the current process or other processes, that is, whether it is the current application or the service or activity of other applications, the message mechanism can be used for communication!

However, one drawback of inter-process communication through the message mechanism is that if the interaction between our activity and service is not a simple activity that enables the service operation, we need to send control requests at any time, therefore, you must ensure that the activity can be connected to the service at any time during service running.

Eg: Music Playing 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. However, it only applies to the communication between activity and service, similar to remote method calls, like access in C/S mode, define an IPC interface by defining the aidl interface file. 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 several milliseconds to complete, you should avoid calling in the main thread of the activity, otherwise, the IPC call will suspend the application and cause the interface to lose response. In this case, consider a single thread to process IPC access.

The IPC between two processes looks like a process enters another process to execute code and then returns the execution result.

The IPC Mechanism encourages us to "use existing functions as much as possible, and collaborate with programs that contain existing functions 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 interfaceIdatetimeserviceExtends Android. OS. iinterface
{
...
Public static abstract classStub
Extends Android. OS. Binder
Implements com. myq. Android. multiprocesstest. idatetimeservice
{
...
// Obtain the instance method asinterface
Public static com. myq. Android. multiprocesstest. idatetimeserviceAsinterface(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:
A lot of information on the Internet does not cover the specific description of aidl called by IPC!
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.