Link: http://blog.csdn.net/xieqibao/article/details/6570080
I.Windows, WindowManager and Window management for Android
In fact, windows and views are actually displayed to users in android. The role of activity in android is mainly to solve some logic problems, such as lifecycle management and window creation. In android, window management is an important part, because it is directly responsible for displaying the content to the user and interacting with the user. Respond to user input.
When talking about window management, it is necessary to first talk about the ViewManager interface, which mainly includes the following implementation sub-interfaces and implementation classes: WindowManager and ViewGroup there are three important methods:
* AddView ();
* UpdateViewLayout ();
* RemoveView ();
In WindowManager, The addView method adds the top-level view (DecorView) in the main window to WindowManager and creates a session. Next, we will introduce it in detail. Let's take a look at Window.
Window:
Window is the Window in android, which indicates the top-level Window, that is, the main Window. It has two implementation classes: PhoneWindow and MidWindow. Generally, the activity corresponds to PhoneWindow, setContentView and other methods frequently used in the activity are also implemented in this.
@ Override
Public void setContentView (View view, ViewGroup. LayoutParams params ){
If (mContentParent = null ){
InstallDecor ();
} Else {
MContentParent. removeAllViews ();
}
MContentParent. addView (view, params );
Final Callback cb = getCallback ();
If (cb! = Null ){
Cb. onContentChanged (); // updated when the window class capacity changes
}
}
Each main window has a View, called DecorView, which is the top-level view (actually the ViewGroup) in the main window. There are two member variables in the View: mParent, mChildren, it is used to manage the parent-child relationship of a view. ViewGroup manages a group of views. Therefore, the relationship between all views is established in ViewGroup. The ViewGroup is attached to the main window. In this way, it is easy to find the specific View through findViewById in the window. Event Processing in view is also based on this path.
Let's take a look at two important methods in ActivityThead (ActivityThead will be detailed in an article ):
Define mlaunchactivity ();
HandleResumeActivity ();
In javasmlaunchactivity, the activity. attach method is called to create a window. When the activity is started in the handleResumeActivity method, the main window is added to WindowManager.
View decor = r. window. getDecorView (); // obtain the top-level View of the window.
Decor. setVisibility (View. INVISIBLE );
ViewManager wm = a. getWindowManager (); // WindowManager inherits from ViewManager
WindowManager. LayoutParams l = r. window. getAttributes ();
A. mDecor = decor;
L. type = WindowManager. LayoutParams. TYPE_BASE_APPLICATION;
L. softInputMode | = forwardBit;
If (a. mVisibleFromClient ){
A. mWindowAdded = true;
Wm. addView (decor, l); // Add the top-level view of the main window to WindowMangaer
}
Let's take a look at WindowManager.
WindowManager:
WindowManager is mainly used to manage the status, attributes, view addition, deletion, update, window order, and message Collection and Processing of windows.
You can use Context. getSystemService (Context. WINDOW_SERVICE) to obtain the WindowManager instance.
WindowManager is inherited from ViewManager, which involves three important window management methods:
* AddView ();
* UpdateViewLayout ();
* RemoveView ();
There is also an important static class LayoutParams in WindowManager. It can be used to set and obtain some properties of the current window.
Let's take a look at the addView () method. In addView, LayoutParams is used to obtain the View attribute of the window and ViewRoot is created for each window. ViewRoot is a bridge between the View and WindowManager, to pass a View to WindowManager, you can use the setView () method of ViewRoot to transmit messages between View and WindowManager. When you add the main window to WindowManger, it first creates a proxy object:
Wm = (WindowManagerImpl) context. getSystemService (Context. WINDOW_SERVICE)
And enable the session (IWindowSession). Then, Window will establish a connection with WindowManager through this session,
Let's take a look at the setView method:
Try {
Res = sWindowSession. add (mWindow, m1_wattributes,
GetHostVisibility (), mAttachInfo. mContentInsets );
} Catch (RemoteException e ){
MAdded = false;
MView = null;
MAttachInfo. mRootView = null;
UnscheduleTraversals ();
Throw newRuntimeException ("Adding window failed", e );
} Finally {
If (restore ){
Attrs. restore ();
}
}
In this Code, ViewRoot adds the window to WindowManager through IWindowSession. ViewRoot inherits Handler. In fact, ViewRoot is essentially a Handler. In a window, ViewRoot handles View event processing, message sending, and callback.
In this way, the window is added to WindowManager, and the window view, events, and message collection and processing are managed by WindowManager.
II. Management and creation of ActivityThead, ActivityManagerService, and activity in Android
In android, Activity is one of the four most important components (of course, others are also important). How does android manage these activities? How is the application process and main thread created, and when is the application message loop created? This article will introduce in detail:
First, let's take a look at the classes involved. The following class diagrams give a general impression on the whole:
ActivityThread:
ActivityThread is mainly used to start the main thread of an application and manage the activity that the application is dealing. All activity information on the Application end is stored in the ActivityThread member variable mActivities.
Final HashMap <IBinder, ActivityRecord> mActivities = new HashMap <IBinder, ActivityRecord> ();
That is to say, in mActivities, all activity instance records created by the application are recorded, corresponding to ActivityRecord.
How does ActivityThread start the application? ActivityThread has a main function. In this function, the application is started and the message loop is established. As mentioned earlier, the system will automatically create a message loop for the main thread.
/*** Application startup entry. The System Automatically Establishes a message loop mechanism when the main thread starts. */
Public static final void main (String [] args ){
SamplingProfilerIntegration. start ();
Process. setArgV0 ("<pre-initialized> ");
Lorule. preparemainlorule ();
ActivityThread thread = new ActivityThread ();
Thread. attach (false );
Logoff. loop ();
If (Process. supportsProcesses ()){
Throw new RuntimeException ("Main thread loop unexpectedly exited ");
}
Thread. detach ();
String name = (thread. mInitialApplication! = Null )? Thread. mInitialApplication
. GetPackageName (): "<unknown> ";
Slog. I (TAG, "Main thread of" + name + "is now exiting ");
}
Before a message loop is established, the runtime environment of the application is initialized through thread. attach (false), and The thread between activityThread and ActivityManagerService is established. mAppThread is an instance of IApplicationThread.
Android. ddm. DdmHandleAppName. setAppName ("<pre-initialized> ");
RuntimeInit. setApplicationObject (mAppThread. asBinder ());
IActivityManager mgr = ActivityManagerNative. getDefault ();
Try {
Mgr. attachApplication (mAppThread );
} Catch (RemoteException ex ){
}
Note: Each application corresponds to an ActivityThread instance, and the ActivityThread. main opens the message loop. Each application also corresponds to an ApplicationThread object. This object is a bridge between activityThread and ActivityManagerService.
In attach, another thing is to call attachApplication through a proxy and establish ProcessRecord information in ActivityManagerService by using the binder's transact mechanism.
Then, the ProcessRecord can be used to obtain all the ActivityRecord records in the ActivityThread. The following section describes how to create an ECS instance.
ActivityManagerService:
In ActivityManagerService, there is also a place for activity management: mHistory stack, which stores the HistoryActivity (class HistoryRecord extendsIApplicationToken. Stub) of the server ). The activity at the top of the stack is in the current running state.
Let's take a look at the request process of the startActivity method of the Activity:
From the time sequence diagram, we can see that the Activity. startActivity () method is finally executed in the ActivityManagerService. startActivity method through the proxy class and Binder Mechanism.
What are the main things in startActivity of ActivityManagerService? Let's take a look at the important code snippet:
- Create HistoryRecord instance r based on activity, ProcessRecord, and other information
- HistoryRecord r = new HistoryRecord (this, callerApp, callingUid, intent, resolvedType, aInfo, mConfiguration, resultRecord, resultWho, requestCode, componentSpecified );
- MHistory. add (addPos, r );
After an activity is added to mHistory, it indicates that the activity record can be found on the server, but the activity record is not found on the client. You also need to use the thread (IApplication) variable in ProcessRecord to call its scheduleLaunchActivity method to create a new ActivityRecord record in ActivityThread (as we have said before, the client activity is recorded using ActivityRecord, and put it in mActivities ).
- App. thread. scheduleLaunchActivity (new Intent (r. intent), r, System. identityHashCode (r), r.info, r. icicle, results, newIntents ,! AndResume, isNextTransitionForward ());
Main class diagrams involved:
Let's take a look at the scheduleLaunchActivity method in ApplicationThread:
- Public final void scheduleLaunchActivi (Intent intent, IBinder token, int ident, ActivityInfo info, Bundle state, List <ResultInfo> pendingResults, List <Intent> pendingNewIntents,
- Boolean notResumed, boolean isForward ){
- ActivityRecord r = new ActivityRecor ();
- R. token = token;
- R. ident = ident;
- R. intent = intent;
- R. activityInfo = info;
- R. state = state;
- R. pendingResults = pendingResults;
- R. pendingIntents = pendingNewIntents;
- R. startsNotResumed = notResumed; r. isForward = isForward; queueOrSendMessage (H. LAUNCH_ACTIVITY, r );}
In this example, the client activity record ActivityRecord is created based on the information returned by the server, and messages are sent to the Message Queue through Handler to enter the message loop. Process messages in ActivityThread. handleMessage. In the handleLaunchActivity method, the ActivityRecord record is added to mActivities (mActivities. put (r. token, r), and start the activity (involving window, view, windowManager. For details, see the handleResumeActivity () method and the previous introduction to window and WindowManager)
Summary:
- There is a place for activity management on the client and the server respectively. The server is in mHistory, and the activity that is at the top of the mHistory stack is in the running status, and the client is in mActivities.
- At startActivity, HistoryRecord is created in ActivityManagerService and added to mHistory. Then, the ActivityRecord record is created on the client through scheduleLaunchActivity and added to mActivities. Finally, the ActivityThread initiates a request, enters the message loop, and completes activity startup and window management.