CN

Android App Launch Optimization: Implementation and Principles of DelayLoad (...

Word count: 2.8kReading time: 17 min
2015/12/29
loading

In the previous article, we tried the third DelayLoad approach. That article showed the code; here I want to follow what happens when it runs.

That takes us through several Android framework classes and Activity lifecycle methods.

I found tracing it quite fun: use the tools, add some debug code, and follow it one step at a time. Doing that helped me understand Activity startup better. I hope walking through it helps you too.

Version note (reviewed 2026-10-13): This preserves the historical startup path, using AOSP android-5.1.1_r1 for platform code. The two support-v7 methods are checked against the support repository’s android-6.0.1_r1 tag, not an assertion about the app’s original Maven dependency version. The final section covers Android 16, Android 12 SplashScreen, and current tools. Nested posts can alter ordering under particular queue conditions; they do not guarantee that the first frame is visible. Framework excerpts below are not standalone app examples.

In the previous article, the core method of DelayLoad we ultimately used was to add the following method in the Activity’s onCreate function:

1
2
3
4
5
6
getWindow().getDecorView().post(new Runnable() {
@Override
public void run() {
myHandler.post(mLoadingRunnable);
}
});

Here myHandler should be an ordinary synchronous Handler explicitly bound to the main thread, such as new Handler(Looper.getMainLooper()). Both Runnables still execute on the UI thread; the completed cancellable example is in Part 1. Now follow the relevant classes and methods.

1. Activity.getWindow and PhoneWindow Initialization Timing

In this platform implementation, an ordinary Activity’s getWindow() returns its Window, implemented by PhoneWindow:

1
2
3
public Window getWindow() {
return mWindow;
}

mWindow is created in Activity.attach(). This excerpt shows window creation only; the factory method belongs to a different class:

1
2
3
4
5
6
7
// Activity.attach(): window-creation excerpt
attachBaseContext(context);
mFragments.attachActivity(this, mContainer, null);
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);

PolicyManager.makeNewWindow() delegates to Policy.makeNewWindow():

1
2
3
public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
}

ActivityThread calls activity.attach() before Instrumentation invokes onCreate(). This connects the Activity object to framework state; it does not mean its DecorView is attached to a window.

Summary:

  • An ordinary Activity owns its application window. Dialog and system starting windows are separate, so there is no universal one-to-one mapping between every PhoneWindow and Activity in the system.
  • Android describes PhoneWindow as an “Android-specific Window.”
  • PhoneWindow has many methods that everyone is relatively familiar with, such as setContentView/addContentView, etc.; it also has several important internal classes, such as: DecorView;

2. PhoneWindow.getDecorView and DecorView Initialization Timing

Earlier we said that DecorView is an internal class of PhoneWindow, and its definition is as follows:

1
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker

DecorView is created on demand in this version. The first getDecorView(), setContentView(), or another install path can trigger installDecor(). The old android.support.v7.app.AppCompatActivity in the example accesses decor through its delegate during super.onCreate(), producing the chain below. This is not a universal creation point for every Activity subclass or release:

1
2
3
4
5
protected void onCreate(@Nullable Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}

In the checked support tag, AppCompatDelegateImplV7.onCreate() obtains decor directly. It does not include the super.onCreate(savedInstanceState) call shown in the original excerpt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void onCreate(Bundle savedInstanceState) {
mWindowDecor = (ViewGroup) mWindow.getDecorView();

if (mOriginalWindowCallback instanceof Activity) {
if (NavUtils.getParentActivityName((Activity) mOriginalWindowCallback) != null) {
// Peek at the Action Bar and update it if it already exists
ActionBar ab = peekSupportActionBar();
if (ab == null) {
mEnableDefaultActionBarUp = true;
} else {
ab.setDefaultDisplayHomeAsUpEnabled(true);
}
}
}
}

That is, here’s mWindow.getDecorView(), which instantiates the DecorView:

1
2
3
4
5
6
public final View getDecorView() {
if (mDecor == null) {
installDecor();
}
return mDecor;
}

installDecor() creates the root View through generateDecor() and builds the application window’s decor/content container through theme-driven generateLayout(). It does not insert the system StartingWindow into this app DecorView. The old PhoneWindowManager.addStartingWindow() creates a separate Window with TYPE_APPLICATION_STARTING. They can use the same app theme without being the same window.

Summary

  • Decor has the meaning of decoration. DecorView’s official comment is “This is the top-level view of the window, containing the window decor.” We can understand that DecorView is the layout at the very bottom of our current Activity. So when we open DDMS to view the Tree Overview, we can discover that the rootmost View is the DecorView:
    DelayLoad
  • Legacy starting previews depend on theme properties such as android:windowBackground; an unspecified background is not guaranteed to be white. A suitable background can improve the blank-screen appearance but does not reduce initialization work. Whether a starting window appears also depends on system policy and window attributes. (Of course, I can understand the widespread SplashActivity + ads approach.) Android 12 system splash screens are covered at the end.

3. Post

When we call DecorView’s Post method, it will ultimately call View’s Post method because DecorView ultimately inherits from View:

1
2
3
4
5
6
7
8
9
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Assume that post will succeed later
ViewRootImpl.getRunQueue().post(action);
return true;
}

For the ordinary newly created Activity path here, decor has not yet been added to the window during onCreate(), so this View’s mAttachInfo is null. Do not infer the same state for every View from a lifecycle callback name: an already attached View posts directly to its associated Handler.

What do the Activity callbacks actually do? When writing an app, it can feel as though everything happens in onCreate. onStart? onResume? We may barely touch them. But the framework still has work to do there.

PhoneWindow was created earlier in Activity.attach(). Decor and content Views can be created during onCreate(), but construction is not window attachment, layout, or presentation. In this old ActivityThread’s ordinary visible-start path, handleResumeActivity() calls the resume logic and then adds decor through WindowManager. Creating ViewRootImpl and a hardware renderer also depends on window and acceleration conditions; onResume() itself is not a completion guarantee.

ActivityThread.handleResumeActivity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
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);
}
}

wm.addView(decor, l) reaches WindowManagerGlobal.addView() through WindowManagerImpl. These excerpts show root creation, registration, and the later setView call; lock and exception-handling scopes are in the full source:

1
2
3
4
5
6
7
8
9
// WindowManagerGlobal.addView(): registration excerpt, inside its lock
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);

// Later, outside that lock, inside the original try/catch:
root.setView(view, wparams, panelParentView);

We know that ViewRootImpl is a core class in the View system, and its definition is as follows:

1
2
public final class ViewRootImpl implements ViewParent,
View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks

ViewRootImpl creates its View.AttachInfo in its constructor, but that does not immediately assign it to every View. During the first traversal, host.dispatchAttachedToWindow(mAttachInfo, 0) propagates it through the tree; View.dispatchAttachedToWindow() assigns the View’s mAttachInfo. Root state existing and a particular View being attached are different events.

Continuing with addView’s root.setView(view, wparams, panelParentView); the view passed in is decorView, and root is ViewRootImpl. This function sets ViewRootImpl’s mView variable to the passed-in view—that is, the decorView. So now the relationship between ViewRootImpl and DecorView is also clear.

Returning to post, this old unattached-View path uses ViewRootImpl.getRunQueue(). It is neither the Looper MessageQueue nor a private queue per ViewRootImpl instance: static sRunQueues is a ThreadLocal<RunQueue>, reused by calls on the same thread. This discussion assumes calls on the UI thread, not arbitrary background-thread access to Views.

The following excerpts show RunQueue posting and forwarding members; its HandlerAction type and cancellation methods are in the full source:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();

void post(Runnable action) {
postDelayed(action, 0);
}

void postDelayed(Runnable action, long delayMillis) {
HandlerAction handlerAction = new HandlerAction();
handlerAction.action = action;
handlerAction.delay = delayMillis;

synchronized (mActions) {
mActions.add(handlerAction);
}
}

void executeActions(Handler handler) {
synchronized (mActions) {
final ArrayList<HandlerAction> actions = mActions;
final int count = actions.size();

for (int i = 0; i < count; i++) {
final HandlerAction handlerAction = actions.get(i);
handler.postDelayed(handlerAction.action, handlerAction.delay);
}

actions.clear();
}
}

This branch stores the Runnable and relative delay in HandlerAction. executeActions(handler) later forwards each item with handler.postDelayed and clears the temporary list; it does not execute the Runnables inline. In this old unattached-View postDelayed path, the delay starts again when forwarded to the Handler, rather than forming a precise timer from the original call.

So when is the executeActions method executed? And which Handler is the passed-in Handler?

4. PerformTraversals

performTraversals() measures, lays out, and draws as required by state. Every frame need not perform all three, and RenderThread-driven animation frames need not rerun UI traversal. The old RunQueue forwarding occurs here:

The executeActions we discussed in the previous section is executed within performTraversals:

1
2
// Execute enqueued actions on every traversal in case a detached view enqueued an action
getRunQueue().executeActions(mAttachInfo.mHandler);

We can see that the Handler passed in here is mAttachInfo.mHandler. In the previous section, we mentioned that mAttachInfo is initialized together when ViewRootImpl is initialized:

1
mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);

The mHandler here is a ViewRootHandler object:

1
final ViewRootHandler mHandler = new ViewRootHandler();

ViewRootHandler extends Handler without explicitly supplying a Looper in this tag. A default Handler binds to the creating thread’s Looper, not automatically to mainLooper. This ordinary Activity path creates ViewRootImpl on the main thread, so it uses the main Looper. A thread without a Looper would cause that constructor to throw.

On this old UI-thread/first-attachment path, the next performTraversals() forwards the outer Runnable to the main queue. It can run only after the current call stack returns. That explains the first post, but not yet why the second post sometimes lands after another traversal.

After that detour, we’ve finally explained the line at the start. I did ramble a bit, and I suspect few people will have the patience to get this far. If you’re still here, add an index++ in the comments. Let’s start at index = 0 and see how many people made it.

5. UpdateText

A reader asked in the comments on Part 1: why post again inside run() instead of calling updateText directly? We need to follow the sequence a little further to answer that.

Part 1 observed updateText after a later traversal when using two posts. Old source contains conditions that explain such ordering, but “EGL initialization always causes two traversals” is too broad.

In android-5.1.1_r1, acquiring a valid Surface during relayout when there was none sets newSurface = true. The source explains that drawing is deferred and another traversal scheduled so WindowManager can learn about the windows to display; hardware-renderer initialization also occurs in that branch. Pre-draw cancellation, visibility, skipDraw, and other state still affect drawing. Two is not a universal startup count.

Synchronization barriers are the other condition. scheduleTraversals() inserts a barrier when arranging traversal:

1
2
3
4
5
6
7
8
9
10
11
12
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
}
}

doTraversal() removes its barrier before entering performTraversals():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);

if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}

Trace.traceBegin(Trace.TRACE_TAG_VIEW, "performTraversals");
try {
performTraversals();
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}

if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}

When the queue head is a barrier with a null target, MessageQueue looks for an asynchronous message instead of dispatching ordinary synchronous messages behind it. Choreographer marks its VSYNC message asynchronous, so it can pass. Asynchronous messages can still run on the same main thread; this does not mean background execution.

For one source-supported ordering consistent with the observation, label the outer task A and the updateText task C:

  1. The first traversal forwards pending A to the main queue.
  2. That traversal schedules another traversal because of newSurface or related conditions and inserts barrier B. A is already before B.
  3. A runs and posts C through an ordinary Handler. C lands behind B and cannot yet be dispatched.
  4. An asynchronous frame message runs. The next doTraversal() removes B and performs traversal.
  5. C can run after that main-thread call stack returns. GPU, SurfaceFlinger, and display work may still be in progress.

This requires the relevant implementation, an unattached-View posting path, the A/B/C ordering, a synchronous Handler, and a subsequent traversal actually being scheduled. The original image lacks complete queue logs, so it does not prove this arrangement for every launch. An attached View, asynchronous Handler, or other scheduling state changes the outcome. Apps should not use internal barrier APIs to manufacture a post-first-frame callback.

6. Summary

DelayLoad is a small example. What I wanted to show is how to investigate an implementation or optimization you don’t yet understand. Here we used Systrace and Method Trace, along with building and debugging the source.

Regarding the use of Systrace and Method Trace, there will be detailed articles introducing them later. These two tools are very helpful for understanding source code and some technical implementations.

Systrace

Systrace

Method Trace

Method Trace

Source Code Compilation and Debugging

Source Code Compilation and Debugging

Code

The code involved in this article has been uploaded to GitHub:
https://github.com/Gracker/DelayLoadSample

The project’s 62e03ae snapshot now uses one image and an IdleHandler example, with getWidth() incorrectly used for height. Part 1 explains the differences and provides the corrected three-pair example.

7. 2026 Update

  • Android 16 / android-16.0.0_r1: DecorView is now the separate com.android.internal.policy.DecorView class. An unattached View keeps actions in its own HandlerActionQueue, forwarding them during dispatchAttachedToWindow. The old ThreadLocal RunQueue reasoning does not transfer unchanged. Handler.createAsync, available from API 28, bypasses synchronization barriers; it is not a background executor for startup delays.
  • Android 12 / API 31 onward: The system SplashScreen adds new API boundaries to the old starting-window/theme-preview discussion. Follow the official migration guidance and the appropriate windowSplashScreenBackground, postSplashScreenTheme, and related attributes. Changing old windowBackground alone is not the whole configuration, and a separate SplashActivity can produce duplicate splash screens. Keeping a splash visible does not reduce initialization time.
  • Tools: Android Device Monitor was deprecated in Android Studio 3.1 and removed in 3.2. Use Layout Inspector for hierarchy inspection, Perfetto/System Trace for system timing, and the current Profiler for method analysis. The original screenshots are historical, not current tool UI. Instrumented method tracing and debug logging add overhead and should not be treated as an unperturbed startup benchmark.
  • Choose the right condition: Use layout callbacks for dimensions; even API 29 frame-commit callbacks do not guarantee visible pixels. See Part 1 for examples. Validate initial display, full usability, and subsequent frames instead of substituting traversal counts or Runnable completion for presentation evidence.

Sources


About Me && Blog

Below is a personal introduction and related links. I look forward to communicating with colleagues in the same field. When three walk together, there must be my teacher!

  1. Blogger Personal Introduction: Inside are personal WeChat and WeChat group links.
  2. Blog Content Navigation: A navigation of personal blog content.
  3. Personally Organized and Collected Excellent Blog Articles - Essential Skills and Tools for Android Performance Optimization: Everyone is welcome to self-recommend and recommend (private WeChat chat is fine).
  4. Android Performance Optimization Knowledge Planet: The paid community stopped operating in 2026 and no longer accepts new members; this link preserves its history.

“If you want to go fast, go alone. If you want to go far, go together.”

Wechat QR

CATALOG
  1. 1. 1. Activity.getWindow and PhoneWindow Initialization Timing
    1. 1.1. Summary:
  2. 2. 2. PhoneWindow.getDecorView and DecorView Initialization Timing
    1. 2.1. Summary
  3. 3. 3. Post
  4. 4. 4. PerformTraversals
  5. 5. 5. UpdateText
  6. 6. 6. Summary
    1. 6.1. Systrace
    2. 6.2. Method Trace
    3. 6.3. Source Code Compilation and Debugging
    4. 6.4. Code
  7. 7. 7. 2026 Update
    1. 7.1. Sources
  • About Me && Blog