Android-launcher Startup Process Analysis

Source: Internet
Author: User
Tags event listener

Step 1: Start With launcherapplication. Java and find the oncreate () method first:

Public void oncreate () {// set the minimum heap memory to 8 m vmruntime. getruntime (). setminimumheapsize (8*1024*1024); // LLX modify the heapsize super. oncreate (); // create the application Icon cache miconcache = new iconcache (this); // create launchermodel Mmodel = new launchermodel (this, miconcache ); // register intent receivers // register intent. action_package_added, intent. action_package_removed, // intent. action_external_applications_available, // intent. action_locale_changed event listener // launchermodel listens for the above event as a broadcast receiver intentfilter = new intentfilter (intent. action_package_added); filter. addaction (intent. action_package_removed); filter. addaction (intent. action_package_changed); filter. adddatascheme ("package"); registerreceiver (Mmodel, filter); filter = new intentfilter (); filter. addaction (intent. action_external_applications_available); filter. addaction (intent. action_external_applications_unavailable); registerreceiver (Mmodel, filter); filter = new intentfilter (); filter. addaction (intent. action_locale_changed); registerreceiver (Mmodel, filter); // register for changes to the favorites // Add the contentresolver resolver = getcontentresolver (); resolver. registercontentobserver (launchersettings. favorites. content_uri, true, mfavoritesobserver );}

Step 2: Check the oncreate () method in launcher. Java:

Protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); // obtain the launcherapplication APP = (launcherapplication) getapplication (); Mmodel = app. setlauncher (this); miconcache = app. geticoncache (); // create a drag-and-drop controller. New dragcontroller (this) mdragcontroller = new dragcontroller (this); minflater = getlayoutinflat Er (); // obtain the Desktop component manager and start the Desktop component host mappwidgetmanager = appwidgetmanager. getinstance (this); mappwidgethost = new launcherappwidgethost (this, appwidget_host_id); mappwidgethost. startlistening (); If (profile_startup) {android. OS. debug. startmethodtracing ("/sdcard/launcher");} // from array. hotseats load all hotseats loadhotseats (); // set checkforlocalechange (); setwallpaperdimension (); // load the layout file setcontentview (R. Layout. launcher); // Initialize all controls setupviews (); snapshots (); lockallapps (); // obtain desktop persistent data from bundle savedinstancestate msavedstate = savedinstancestate; restorestate (msavedstate ); if (profile_startup) {android. OS. debug. stopmethodtracing ();} If (! Mrestoring) {// launchermodel. loader. startloader () Code Synchronization Mmodel. startloader (this, true);} // for handling default keys mdefaultkeyssb = new spannablestringbuilder (); selection. setselection (mdefakeykeyssb, 0); // register intent. action_close_system_dialogs broadcast listening intentfilter filter = new intentfilter (intent. action_close_system_dialogs); registerreceiver (mclosesystemdialogsreceiver, filter );}

Step 3: load the desktop items: the run method of the thread in launchermodel. Java starts loading only after the main thread is completed.

Public void run () {// optimize for end-user experience: If the launcher is up and // running with the // All Apps interface in the foreground, load all apps first. otherwise, load the // workspace first (default ). final callbacks CBK = mcallbacks. get (); Final Boolean loadworkspacefirst = CBK! = NULL? (! CBK. isallappsvisible (): true; keep_running: {// elevate priority when home launches for the first time to avoid // starving at boot time. staring at a blank home is not cool. synchronized (mlock) {android. OS. process. setthreadpriority (mislaunching? Process. thread_priority_default: process. thread_priority_background);} // determine whether to first load the desktop if (loadworkspacefirst) {If (debug_loaders) log. D (TAG, "Step 1: loading workspace"); // launcher from the database. all the desktop items in the DB query construct corresponding iteminfo objects and store them in loadandbindworkspace ();} else {If (debug_loaders) log. D (TAG, "Step 1: Special: loading all apps"); loadandbindallapps ();} If (mstopped) {break keep_running;} // Whew! Hard work done. slow us down, and wait until the UI thread has // settled down. synchronized (mlock) {If (mislaunching) {android. OS. process. setthreadpriority (process. thread_priority_background) ;}} waitforidle (); // second step if (loadworkspacefirst) {If (debug_loaders) log. D (TAG, "Step 2: loading all apps"); loadandbindallapps ();} else {If (debug_loaders) log. D (TAG, "Step 2: Special: loading workspace"); loadandbindworkspace ();}}

The startbinding method in launcher. Java is called here.

public void startBinding() {        final Workspace workspace = mWorkspace;        int count = workspace.getChildCount();        for (int i = 0; i < count; i++) {            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().            ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();        }        if (DEBUG_USER_INTERFACE) {            android.widget.Button finishButton = new android.widget.Button(this);            finishButton.setText("Finish");            workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);            finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {                public void onClick(View v) {                    finish();                }            });        }    }

There is also the binditem () method of launcher. Java:

Public void binditems (arraylist <iteminfo> shortcuts, int start, int end) {setloadonresume (); // obtain the celllayout object of the desktop, that is, one final workspace = mworkspace in the five user desktops in the workspace; For (INT I = start; I <end; I ++) {// create the desktop icon view object final iteminfo item = shortcuts Based on the iteminfo object. get (I); mshorttopitems. add (item); Switch (item. itemtype) {Case launchersettings. favorites. item_type_application: Case launchersettin GS. favorites. item_type_shortcut: final view shortcut = createshortcut (shortcutinfo) item); // get item. screen, item. cellx, item. celly, spanx, and spany are added to the screen. Workspace. addinscreen (shortcut, item. screen, item. cellx, item. celly, 1, 1, false); break; Case launchersettings. favorites. item_type_user_folder: Final foldericon newfolder = foldericon. fromxml (R. layout. folder_icon, this, (viewgroup) workspace. getchildat (workspace. getcurrentscreen (), (userfolderinfo) item); workspace. addinscreen (newfolder, item. screen, item. cellx, item. celly, 1, 1, false); break; Case launchersettings. favorites. item_type_live_folder: Final foldericon newlivefolder = livefoldericon. fromxml (R. layout. live_folder_icon, this, (viewgroup) workspace. getchildat (workspace. getcurrentscreen (), (livefolderinfo) item); workspace. addinscreen (newlivefolder, item. screen, item. cellx, item. celly, 1, 1, false); break ;}}//. reset the layoutparam (type: celllayout) of the desktop icon view. layoutparam) workspace. requestlayout ();}

Note that both methods are called asynchronously. The reason should be clear: time.

Pay attention to the following two points:

1. Add onlongclicklistener = laucher to the desktop icon view object. The laucher monitors the longclick event of the desktop icon view.

2. If the desktop icon is a droptarget object, drag and drop the Controller mdragcontroller to add the view to the drag and drop destination list.

In the launcher. Java code, the bindfolders () and bindappwidget () methods are both callback methods. Let's take a look at the bindappwidget () method.

/*** Add the views for a widget to the workspace. ** implementation of the method from launchermodel. callbacks. */Public void bindappwidget (launcherappwidgetinfo item) {setloadonresume (); Final long start = debug_widgets? Systemclock. uptimemillis (): 0; If (debug_widgets) {log. D (TAG, "bindappwidget:" + item);} final workspace = mworkspace; // obtain the appwidgetid final int appwidgetid of launcherappwidgetinfo = item. appwidgetid; // create the view appwidgethostview object final appwidgetproviderinfo appwidgetinfo = mappwidgetmanager for the Desktop component based on appwidgetinfo. getappwidgetinfo (appwidgetid); If (debug_widgets) {log. D (TAG, "bindappwidget: Id =" + item. appwidgetid + "belongs to component" + appwidgetinfo. provider);} item. hostview = mappwidgethost. createview (this, appwidgetid, appwidgetinfo); item. hostview. setappwidget (appwidgetid, appwidgetinfo); item. hostview. settag (item); // Add it to the cell Workspace of the corresponding desktop. addinscreen (item. hostview, item. screen, item. cellx, item. celly, item. spanx, item. spany, false); workspace. requestlayout (); mshorttopitems. add (item); If (debug_widgets) {log. D (TAG, "bound widget id =" + item. appwidgetid + "in" + (systemclock. uptimemillis ()-Start) + "Ms ");}}

After loading is complete, finishbindingitems () will be executed ():

/**     * Callback saying that there aren't any more items to bind.     *     * Implementation of the method from LauncherModel.Callbacks.     */    public void finishBindingItems() {        setLoadOnResume();        if (mSavedState != null) {            if (!mWorkspace.hasFocus()) {                mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();            }            final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);            if (userFolders != null) {                for (long folderId : userFolders) {                    final FolderInfo info = sFolders.get(folderId);                    if (info != null) {                        openFolder(info);                    }                }                final Folder openFolder = mWorkspace.getOpenFolder();                if (openFolder != null) {                    openFolder.requestFocus();                }            }            mSavedState = null;        }        if (mSavedInstanceState != null) {            super.onRestoreInstanceState(mSavedInstanceState);            mSavedInstanceState = null;        }        mWorkspaceLoading = false;    }

The first three are all callback methods. The controller is of course launchermodel. java. Let's take a look at the Code:

Its interface is defined as follows:

public interface Callbacks {        public boolean setLoadOnResume();        public int getCurrentWorkspaceScreen();        public void startBinding();        public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);        public void bindFolders(HashMap<Long,FolderInfo> folders);        public void finishBindingItems();        public void bindAppWidget(LauncherAppWidgetInfo info);        public void bindAllApplications(ArrayList<ApplicationInfo> apps);        public void bindAppsAdded(ArrayList<ApplicationInfo> apps);        public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);        public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent);        public boolean isAllAppsVisible();    }

If you want to take a closer look, you can find it in the code.

Finally, run the bindallapplications (), bindincluadded () method:

public void bindAllApplications(ArrayList<ApplicationInfo> apps) {        mAllAppsGrid.setApps(apps);    }    /**     * A package was installed.     *     * Implementation of the method from LauncherModel.Callbacks.     */    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {        setLoadOnResume();        removeDialog(DIALOG_CREATE_SHORTCUT);        mAllAppsGrid.addApps(apps);    }

This is basically the entire startup process.

PS: This article does not have much textual content. For details about the code, see the code annotations. If you have any questions, please leave a message!

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.