Android startup Principle Analysis

Source: Internet
Author: User

Android startup Principle Analysis

We know that Android is based on an Activity, but we do not see how an Activity starts. Let's start with the Android source code today.


When an Android apk is opened, the first class used is this class. Let's talk about this class first. After that, you will be able to understand the startup principles of Android applications. This item is named after a Thread and looks like a Thread class. In fact, it is not a Thread class. This class does not inherit any classes. Or directly inherit from the Object class. Let's take a look at the ActivityThread source code:

public final class ActivityThread {    ....}

This is the source code when ActivityThread is defined. It can be seen that it does not inherit any classes at all. Why does it end with a Thread. It seems unreasonable. Actually not. Probably everyone should adopt the asynchronous thread mechanism of Android. In fact, ActivityThread also starts a thread when it is created. This thread is an asynchronous thread, which creates MessageQueue and performs message polling at the same time, therefore, when this application is running, this thread is always there. This thread is the main thread of the application, and UI processing and so on are all processed in this thread.
In the AcitivityThread class, there is a main method. We know that the main method is the entry to the java application. This is the entry to the program. Let's look at the source code of ActivityThread:

    public static void main(String[] args) {        SamplingProfilerIntegration.start();        // CloseGuard defaults to true and can be quite spammy.  We        // disable it here, but selectively enable it later (via        // StrictMode) on debug builds, but using DropBox, not logs.        CloseGuard.setEnabled(false);        Environment.initForCurrentUser();        // Set the reporter for event logging in libcore        EventLogger.setReporter(new EventLoggingReporter());        Security.addProvider(new AndroidKeyStoreProvider());        Process.setArgV0("
"); // The key part. Check the logoff here. prepareMainLooper (); ActivityThread thread = new ActivityThread (); thread. attach (false); if (sMainThreadHandler = null) {sMainThreadHandler = thread. getHandler ();} AsyncTask. init (); if (false) {logoff. mylogoff (). setMessageLogging (new LogPrinter (Log. DEBUG, "ActivityThread");} logoff. loop (); throw new RuntimeException ("Main thread loop unexpectedly exited ");}

Let's skip the other part first. Let's first look at the key part, which is the place I noted. UseLooper.prepareMainLooper();Method To create a MessageQueue instance. Preparemainloue internally calls the prepare () method to create a Message Queue (MessageQueue ). After being created, an ActivityThread object is created. This ActivityThread object will create a Handler and an ApplicationThread object. These two objects will be introduced later. (here there should be an interrupt vector, or start another thread to explain the Handler object and Application object. After the ActivityThread object is created. The middle part is omitted from the table. Here we will call logoff. loop (), which is a loop in the message queue. Therefore, the ActivityThread is always there, because you need to wait for the messages sent from other threads. This thread is our main thread. The management of activities and services is here. It will be introduced later.
Now, we can talk about Handler and ApplicationThread. In ActivityThread, the Handler is actually an internal class. The class name is H, right, which is a letter of H. It inherits from the Handler object. Let's take a look at the source code:

In row 3, we can see that he created an H class instance. Note: This is the member variable area of the class, not in a method. This indicates that this class is created at the same time as this mH object is created. Therefore, this mH is equivalent to the main thread, which is created in main. This object is used by other threads to send messages to the main thread. Let's take a look at the part we didn't mention in the main function:

      Looper.prepareMainLooper();        ActivityThread thread = new ActivityThread();        thread.attach(false);        if (sMainThreadHandler == null) {            sMainThreadHandler = thread.getHandler();        }        AsyncTa

We can see such a statement in the if statementsMainThreadHandler = thread.getHandler();Thread is the ActivityThread instance just created, and the result returned by the getHandler method is the mH instance.
Next, let's talk about the ApplicationThread class, which is the internal class of ActivityThread. What is the role of this class. In fact, the communication between processes is involved. This class is responsible for receiving remote AmS (ActivitymanagerService) IPC (inter-process communication) calls. This call is generally called by the Android system, which is equivalent to inter-process communication. The Android system has a service used to monitor user operations, when users perform related operations, they will notify the application to respond through communication between processes, such as starting an Activity. When this class receives a notification, the Activity will be scheduled to start. Let's take a look at the source code of this class:

Some of the Code is posted here. Note that not all the code of this class is only part of it. Let's take a look at the second method.
schedulePauseActivityThis method should be "scheduled to suspend the activity". This method is used to allow the Activity to call the onPause code. The other codes below are similar. The code that manages both the service and activity. sendMessage is called internally in these methods, and mh. sendMessage () is called internally in this method (). Schedule messages related to Activity suspension or startup to the MessageQueue queue of the main thread and wait for the message queue to round-robin to process the message. We can also see from the names of these methods that schedule means arrangement. "arrange to suspend activity" means you have to schedule the "Pause activity" event, wait until MessageQueue is finished, and then handle the pause activity. Who is the person who arranged the incident? This is the assistant of mH who sent the message to MessageQueue.

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: 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.