Analyze the intent components in Android from the source code _android

Source: Internet
Author: User
Tags serialization

We know that intent is primarily used to activate Android components, so how exactly is it activated? Can I bring Java objects when I activate? Why should objects be serialized before they are passed?

First, intent official website explanation
intent can be used by startactivity to load an activity, or it can be sent to a specified Broadreceiver component by Broadcastintent,
Or be startservice, bingservice to communicate with the background service.
The main function of intent is to load the activity, like the glue between the actions.
Intent data structure:

    • Action: The action to be performed; (For example: Action_call Create a call Activity;action_battery_low emit a broadcast warning low battery charge)
    • Data: (Uri) to be used;
    • Category: Information about the target component;
    • Component: The class name of the target component;
    • Extras: This is bundle data.

Intent resolution:

    • Explicit intent, specifies the class name of the target component, that is, the component, the target component is known, no parsing is required;
    • Implicit intent, without specifying the target component component, or not knowing or caring who receives the intent, requires Android to resolve the target component itself.

Implicit Intent parsing method:

1. All <intent-filter> and the intent defined therein in Androidmanifest.xml;
2. Find the component that can handle this intent through Packagemanager (get the applications installed by the current device package). Match action, type, category three variables to find.
second, the simple explanation:
Intent can activate the three main components of Andorid: activity, service, and Broadcastreceiver. When using intent, you typically explicitly specify the target component and, if not specified, resolve it based on the action, type, and category three values that are included with the intent to find the components that can be processed.

Third, the question: Intent how realizes the component to switch, the concrete flow?
1, the Basic method: (to start the activity as an example)

Intent i = new Intent (mainactivity.this, targetactivity.class);
StartActivity (i);

2, the instantiation of intent:

/**
* Create a intent, directly specify intent to activate the * * Component Class name * *, without relying on the * * System to resolve * * Appropriate classes to handle intent
* @param packagecontext To execute this Intent context object
* @param CLS Intent the component class name to be activated
*
/Public Intent (Context Packagecontext, Class CLS) { c11/>//creates a component and assigns it to intent's component member
  mcomponent = new ComponentName (Packagecontext, CLS);

3. Start activity

StartActivity (i)->
startactivity (Intent Intent, @Nullable Bundle options)->
Startactivityforresult ( Intent,-1, options)


/** 
*startactivityforresult (Intent intent, int requestcode, @Nullable Bundle options)
* Load an activity and get
the result * @param intent to start intent.
* @param requestcode if greater than 0 will be returned and the view will be displayed only if the return value returns successfully
@param options other information.
*/Public
void Startactivityforresult (Intent Intent, int requestcode, @Nullable Bundle options) {
if (mparent = = null) {//If no parent activity;instrumentation is used to interact with the Program Guide manifest androidmanifest file.
  instrumentation.activityresult ar =
  minstrumentation.execstartactivity (this, Mmainthread.getapplicationthread (), Mtoken, This,intent, Requestcode, Options); Execute startactivity command
... 
} else {//If there is a parent activity if
   (options!= null) {
     Mparent.startactivityfromchild (this, intent, requestcode, options);
   .....
}

4. Execute startactivity Command Core code:
The task of initiating the activity was entrusted to the bottom activitymanagernative.

 Intent.migrateextrastreamtoclipdata ()//To process intent data in bundle for low-level processing Intent.preparetoleaveprocess (); Ready to leave the application process and enter the Activitymanagerservice process (meaning that the bundle data is to be passed between the processes) int result = Activitymanagernative.getdefault ().
StartActivity (Whothread, Who.getbasepackagename (), Intent, intent.resolvetypeifneeded (Who.getcontentresolver ()), token, target!= null? Target.mEmbeddedID:null, Requestcode, 0, NULL, options); Invokes the system's Activity Manager service to start a new activity.
Consider if it is an explicit intent, find the corresponding component class directly (here is the activity component), and if it is implicit intent, for the specified target component class name, automatically application->system search for the appropriate component to process. TODO: specific system-level code is parsed the next time 

The core question: Why can't intent pass objects directly between components and pass the serialization mechanism?
as you can see from the code above, intent leaves the current application process and enters the Activitymanagerservice process (intent.preparetoleaveprocess ()) when it starts another component, which means that The data to be carried by intent can be transmitted between different processes. First we know that Android is based on Linux and that Java objects between different processes cannot be transmitted, so we're going to serialize objects here to implement the transfer of objects between the application process and the activitymanagerservice process.
Parcel or serializable can serialize objects, in which the serializable is easy to use, but not as good as the parcel container, which is an interface specifically launched by the Android system for interprocess communication.

Additional knowledge:
Regular data types can be passed directly between different processes, such as integers, to pass a string as an example, from a process to a B process, only to open the same size space in the memory area of the B process, and then copy the past.
However, objects cannot be passed directly across processes. Even if the member variable value passes past, the member method cannot pass the past, and an error occurs if the B process wants to invoke the member method.
How to pass an object specifically:
1. In process A, the properties of the Non-default values in the class and the unique flags of the classes are packed (this is called serialization);
2. Pass this package to process B;
3. After receiving the package, process B creates the class based on the unique flag of the class (Java reflection mechanism);
4. Then update the property to the class object.
In this way, process A and process B contain two identical class objects.

Intent how to implement object transfer?
Object implements Serializable {...} ; Bundle.putserializable (Key, Object);
Object implements Parcelable {...}; bundle.putparcelable (Key, Object);
Serializable interface: This is a Java serialization technique that serializes Java objects into binary files. Let the object implement the Serializable interface and use ObjectInputStream and ObjectOutputStream to read and write objects.
Parcelable interface: This is the container that Android provides to encapsulate data, and the encapsulated data can be passed through intent or IPC. Only basic types and classes that implement the Parcelable interface can be placed in parcel.
Vi. Serializable interface-Java
belongs to the Java serialization mechanism: Just let the Java class implement the interface, and you can mark the class serializable without implementing any methods.

Class Person implements Serializable {...}
Person per = new person ();
Bundle.putserializable ("person", per); Passes a reference to the person object

Mperson = (person) getintent (). **getserializableextra** (' person ');

Note: If you serialize this here to include references to other classes (such as: Personinfo) within the class person, such as:

Class Person implements Serializable {
   personinf**o info;
}

Then the referenced class must also be serializable, that is, implement the Serializable interface. Because the person object is serialized during serialization, it also serializes the member variable.

Seven, parcelable interface-Android
here around-how to implement object delivery using parcel in Android-briefly explain why.
The first thing to understand is the parcel container inside Android.

A parcel is a container for storing messages (data or object references) that can be transmitted through Ibindler.
A message container used primarily for lightweight, high-performance IPC interprocess communication. In Android, a "process" is a standard Linux process in which a process is generally not accessible to another process's memory area. Through the parcel,android system, the object can be decomposed into serializable and deserialized to achieve interprocess communication.
However, parcel can also be used in-process communication, primarily to deliver data between different components of an application. For example, we can use the intent encapsulation parcel objects to pass between the activity.
In simple terms, the parcel container implements communication within and between processes, and can also implement remote calls.

Specific ways to pass objects between components:

Let the object belonging to pass implement the Parcelable interface;
Realize Describecontents method;
Implement an abstract method Writetoparcel to get the current state of the object and write to a parcel container;
Adds a static domain CREATOR to the target class, which is an object that implements the Parcelable.creator interface;
Adding a parameter to the constructor of a parcel object, creator calls this constructor to reconstruct our object.
Problem:
Why is there a Java serializable interface to create a parcelable interface?
Performance
Although parcelable is more complex to use, it performs better.

Parcelable Restrictions:

When using parcelable to pass a picture bitmap is not ideal, although bitmap also implements the Parcelable interface. A better approach is to pass
Parcelable cannot be used as a regular serialization store, because the Android system version is different and the parcelable implementation is not exactly the same, which may result in the inability to read parcel data.

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.