[Pin to top] android4.0 launcher source code Research

Source: Internet
Author: User
Launcher is the facade of a mobile phone. It is the main function of a program and the most widely used program in daily applications. Therefore, it is very important in application development. The system's launcher source code is well written. It encapsulates a variety of components, controls, interface rendering, and asynchronous data loading. It is worth further study. Because of my limited capabilities and limited time, I am only here to introduce myself and write some preliminary learning experiences. You can also import the source code and study it carefully. I. launcher UIThe following is a basic interface element of launcher. We will start with launcher. xml. Launcher. XML has three files, which correspond to the horizontal screen, vertical screen, and flat layout. We start with the vertical screen, which is similar to other files. Simplified structure
    <DragLayer>        <WorkSpace>            <CellLayout>            <CellLayout>            <CellLayout>            <CellLayout>            <CellLayout>        < /WorkSpace>        <include layout="@layout/hotseat" android:id="@+id/hotseat"/>        <include android:id="@+id/qsb_bar" layout="@layout/qsb_bar" />        <include layout="@layout/apps_customize_pane"  android:id="@+id/apps_customize_pane" />        <include layout="@layout/workspace_cling"  android:id="@+id/workspace_cling"/>        <include layout="@layout/folder_cling" android:id="@+id/folder_cling"/>    </ DragLayer >
In this way, we can see the layout, and then the figure above will be clearer. The root layout of launcher is a draglayer (a drag-and-drop layer). The draglayer contains a workspace called the idle interface. By default, five celllayout interfaces are loaded in the workspace, that is, the default screen is five. Next, let's look at it. There is a hotseat and a qsb_bar. You will find the bottom shortcut button and the top quick search bar. The last three la s are invisible by default. The first appsmize_pane is visible after you click the middle icon under hotseat, and then load all program icons. There are two other cling layers, which are regarded as the mask layer. They are only loaded at the first startup, and there is no chance to load the layer after it is started. Now, we will analyze these components in sequence: 1. draglayerDraglayer inherits framelayout and combines dragcontroller to implement drag-and-drop functions. draglayer monitors the two user events onintercepttouchevent ontouchevent, which are both touch events. The former only exists in viewgroup, used to manage touch events of child controls. When the draglayer receives the two events, it will be handed over to the dragcontroller for processing. The dragcontroller controls the drag-and-drop process based on whether or not the drag-and-drop moderate information controls the control. There are two interfaces, and one interface droptarget, which can be used to implement drag-and-drop components such as workspace and folder. 2. WorkspaceWorkspace inherits pageview, which is a viewgroup that can be displayed by page. Page view mainly provides the snaptopage () method to achieve slide navigation between pages. Workspace implements the dragscroller interface. When dragcontroller handles the move event, it calls the parent class snaptopage () method to implement switching between the left and right sides of the screen. Workspace is a custom layout. This layout defines some of its own attributes. Let's take a look at the definition of workspace in launcher. xml:

     <com.android.launcher2.Workspace        android:id="@+id/workspace"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:paddingTop="@dimen/qsb_bar_height_inset"        android:paddingBottom="@dimen/button_bar_height"        launcher:defaultScreen="2"        launcher:cellCountX="4"        launcher:cellCountY="4"        launcher:pageSpacing="@dimen/workspace_page_spacing"        launcher:scrollIndicatorPaddingLeft="@dimen/workspace_divider_padding_left"        launcher:scrollIndicatorPaddingRight="@dimen/workspace_divider_padding_right">        <include android:id="@+id/cell1" layout="@layout/workspace_screen" />        <include android:id="@+id/cell2" layout="@layout/workspace_screen" />        <include android:id="@+id/cell3" layout="@layout/workspace_screen" />        <include android:id="@+id/cell4" layout="@layout/workspace_screen" />        <include android:id="@+id/cell5" layout="@layout/workspace_screen" />    </com.android.launcher2.Workspace>
From this definition, we can see that workspace removes the middle part after the quick search bar and hotseat (workspace is also full screen, but paddingtop and paddingbottom are set, so they will not overlap with the search bar and hotseat ). All attributes starting with launcher are custom attributes. The default screen is the second screen (starting from screen 0th ). By default, each screen is divided into 4*4 grids. When the workspace is initialized, if the cellcountx and cellcounty attributes are not defined in XML, the default value is 4*4, but if it is a large screen, such as a tablet, it automatically calculates the number of items based on the screen size and Icon size. Pagespacing is the spacing inside the screen, and celllayout is the next step. 3. celllayoutCelllayout does not implement other interfaces, but listens for down events. When you press the button on the screen, you can determine whether there is a point to the control. If yes, set the control information, for example, the number of rows and columns and the height and width records are stored in cellinfo. 4. appscustomizepagedviewAppscustomizepagedview is also a custom view. The parent class and workspace are both pageview and can slide left and right. Click the icon at the center of hotseat on the idle interface. The idle interface is hidden. After a scaling animation is completed, appscustomizepagedview is set to visible. The launcher status is also changed to state. mi_mimize. The menu interface is a tabhost component consisting of tabwidget and appscustomizepagedview. Tabwidget has two items. One is used to display all apps and the other is used to display all widgets. Under tabwidget, appscustomizepagedview is displayed. Now let's take a look at the definition of appscustomizepagedview in XML:
 <com.android.launcher2.AppsCustomizePagedView                android:id="@+id/apps_customize_pane_content"                android:layout_width="match_parent"                android:layout_height="match_parent"                launcher:maxAppCellCountX="@integer/apps_customize_maxCellCountX"                launcher:maxAppCellCountY="@integer/apps_customize_maxCellCountY"                launcher:pageLayoutWidthGap="@dimen/apps_customize_pageLayoutWidthGap"                launcher:pageLayoutHeightGap="@dimen/apps_customize_pageLayoutHeightGap"                launcher:pageLayoutPaddingTop="@dimen/apps_customize_pageLayoutPaddingTop"                launcher:pageLayoutPaddingBottom="@dimen/apps_customize_pageLayoutPaddingBottom"                launcher:pageLayoutPaddingLeft="@dimen/apps_customize_pageLayoutPaddingLeft"                launcher:pageLayoutPaddingRight="@dimen/apps_customize_pageLayoutPaddingRight"                launcher:widgetCellWidthGap="@dimen/apps_customize_widget_cell_width_gap"                launcher:widgetCellHeightGap="@dimen/apps_customize_widget_cell_height_gap"                launcher:widgetCountX="@integer/apps_customize_widget_cell_count_x"                launcher:widgetCountY="@integer/apps_customize_widget_cell_count_y"                launcher:clingFocusedX="@integer/apps_customize_cling_focused_x"                launcher:clingFocusedY="@integer/apps_customize_cling_focused_y"                launcher:maxGap="@dimen/workspace_max_gap" />
Similarly, all attributes starting with launcher are custom attributes. Maxappcellcountx and maxappcellcouny indicate the maximum number of rows and columns of all app icons. Generally, it is set to-1, which indicates no limit. Pagelayoutwidthgap and pagelayoutheightgap indicate the distance between the menu interface and the screen edge, which is usually set to-1 on a small screen. In the flat layout, considering that the user's hands are captured at the screen edge, therefore, a certain margin is set here. Pagelayoutpaddingxxx refers to inner filling, which is the same as the system padding. Widgetcellwithgap and widgetcellheightgap refer to the interval between widgets in the widget list interface, similar to the margin attribute of the system. The widget list page displays rows and columns of widgetcountx and widgetcounty values. 5. hotseat & qsb_bar 6.
The cling function is mainly used to enter the launcher demo interface for the first time. When you enter idle for the first time, the menu for the first time, and the folder for the first time, it will appear. Cling is a full-screen framelayout, which is defined at the bottom of the draglayer, that is, at the top of the interface. Therefore, when it is displayed, it can cover all interfaces. The cling class encapsulates some display logic and touch logic of the mask layer, as well as image recycling. Cling can automatically display corresponding la s on different interfaces or landscape screens and intercept touch events at corresponding locations. After a user clicks, cling colleagues become invisible, and release image resources.
Ii. launcher Data Loading The data provider in launcher is launcherprovider, which is responsible for saving launcher data to the local database. For example, the icon or widget in the column on the screen on the idle interface will be saved to the database (note that the data list on the menu interface will not be saved to the database, instead, it is saved in memory after the first read ). When launcherprovider is initializing, create a database:
 db.execSQL("CREATE TABLE favorites (" +                    "_id INTEGER PRIMARY KEY," +                    "title TEXT," +                    "intent TEXT," +                    "container INTEGER," +                    "screen INTEGER," +                    "cellX INTEGER," +                    "cellY INTEGER," +                    "spanX INTEGER," +                    "spanY INTEGER," +                    "itemType INTEGER," +                    "appWidgetId INTEGER NOT NULL DEFAULT -1," +                    "isShortcut INTEGER," +                    "iconType INTEGER," +                    "iconPackage TEXT," +                    "iconResource TEXT," +                    "icon BLOB," +                    "uri TEXT," +                    "displayMode INTEGER," +                    "scene TEXT" +                    ");");
From this statement, we can see the table structure of the database. After the table is created, launcher loads some XML files with the settings. For example, default_workspace.xml is the default layout file for each screen. During initialization, launcherprovider reads the default_workspace.xml ID and executes two methods. Loadfavorites (dB, ID); loadscene (dB, ID); these two methods read xml configuration information to the database by parsing XML. Therefore, to modify the launcher initialization screen icon distribution, you can modify the default_workspace.xml file. Launcherprovider provides differential data deletion and modification query, and also encapsulates operations such as UI element insertion and deletion, such as addappwidget (), addurishortcut (), addfolder (), etc, these operations only modify data and do not involve operations on the UI. The data loading involved by launcher is basically encapsulated in launchermodel. In addition, before launchermodel has a very important class, we should also mention that it is IteminfoThis class is actually very simple, it is a ing of fields in the database table. In this way, iteminfo serves as a bridge. Launcher needs iteminfo to determine which icon to deploy on the screen, and obtains the corresponding data from launchermodel, while launcermodel goes back to launcherprovider to retrieve the cursor data and convert it to iteminfo data. From this perspective, we can also see how to layer the launcher design, that is, the launcherprovider provides the original database data. After the launchermodel obtains the data needed by the launchermodel and passes it to the launcher, the launcher starts to draw the interface. Because most of the data in launchermodel is asynchronously loaded, there is an important interface for UI callback.
    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 void bindPackagesUpdated();        public boolean isAllAppsVisible();        public void bindSearchablesChanged();        public void clearAndSwitchScene(String scene);    }
Launcher implements this interface and then uses
    public void initialize(Callbacks callbacks) {        synchronized (mLock) {            mCallbacks = new WeakReference<Callbacks>(callbacks);        }    }
It is passed to launchermodel. After the launchermodel loads data through an asynchronous thread, it triggers the callback function execution in the launcher and draws the interface. The binding of interface elements is basically in the loadtask thread.
Iii. launcher data monitoring

In launcher, applications are added, uninstalled, or updated at any time. Therefore, listening to system programs to install and uninstall listeners is essential. Check the code and find that launchermodel itself is the listener we are looking. In the onreceive listener of launchermodel, the action is used to determine whether the application is installed, uninstalled, updated, or installed abnormally. Pass packagename through data. Update memory data in the packageupdatedtask thread. Call back the interface after the data is obtained.
To notify the UI to draw the interface. In the MTK extended launcher, there is also a function that provides unread message reminders, such as unread text messages, unread calls, and unread emails, which will be digitally reminded on the application icon. To implement this function, MTK adds the broadcast receiver mtkunreadloader to listen to unread data. The interface callback is still used here. The interface definition is as follows:
Because this function is newly added, the system does not send broadcast of unread messages. Therefore, MTK is added
Intent. mtk_action_unread_changedThis anction. In short messages, contacts, and emails, new messages, missed calls, and new emails will be broadcast. It will be included when sent
Intent. mtk_extra_unread_numberTo pass the number of unread entries. Applications that support displaying unread records are saved in the unread_support_shortcuts.xml configuration file:
<?xml version="1.0" encoding="UTF-8"?><unreadshortcuts xmlns:launcher="http://schemas.android.com/apk/res/com.android.launcher">     <shortcut        launcher:unreadPackageName="com.android.contacts"        launcher:unreadClassName="com.android.contacts.activities.DialtactsActivity"        launcher:unreadType="0"        launcher:unreadKey="com_android_contacts_mtk_unread" /> <shortcut        launcher:unreadPackageName="com.android.mms"        launcher:unreadClassName="com.android.mms.ui.BootActivity"        launcher:unreadType="0"        launcher:unreadKey="com_android_mms_mtk_unread" /> <shortcut        launcher:unreadPackageName="com.android.email"        launcher:unreadClassName="com.android.email.activity.Welcome"        launcher:unreadType="0"        launcher:unreadKey="com_android_email_mtk_unread" /> <shortcut        launcher:unreadPackageName="com.android.calendar"        launcher:unreadClassName="com.android.calendar.AllInOneActivity"        launcher:unreadType="0"        launcher:unreadKey="com_android_calendar_mtk_unread" />    </unreadshortcuts>
After reading through the loadunreadsupportshortcuts () method, save it in the sunreadsupportshortcuts set. Only applications in this set will update the icon in the upper-right corner of the icon.

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.