Launcher3桌面開發(2)-Launcher3 桌面加載流程分析(上)

主目錄見:Android高級進階知識(這是總目錄索引)
Launcher3源碼地址:Launcher3-master
[This tutorial was written by Ticoo]

省略一萬字前奏

主入口Launcher

LauncherAppState

Launcher的onCreate里比較長,我們依次取代碼片段來分析,看oncrate方法的這一段,初始化LauncherAppState

public void onCreate() {
    ...
    LauncherAppState app = LauncherAppState.getInstance();
    ...
}
    

LauncherAppState是保存一些全局的,核心的對象。主要有整個Launcher的工作臺workspace,Launcher的控制器LauncherModel,應用圖標的緩存機制IconCache,設備的配置信息InvariantDeviceProfile等。

構造方法,首先初始化內存的追蹤器TestingUtils,記錄我們app的內存信息,這個工具在我們開發其他app分析內存信息時也是很有用的。

private LauncherAppState() {
    ...

    if (TestingUtils.MEMORY_DUMP_ENABLED) {
        TestingUtils.startTrackingMemory(sContext);
    }

    mInvariantDeviceProfile = new InvariantDeviceProfile(sContext);
    mIconCache = new IconCache(sContext, mInvariantDeviceProfile);
    mWidgetCache = new WidgetPreviewLoader(sContext, mIconCache);

    mAppFilter = AppFilter.loadByName(sContext.getString(R.string.app_filter_class));
    mModel = new LauncherModel(this, mIconCache, mAppFilter);

    LauncherAppsCompat.getInstance(sContext).addOnAppsChangedCallback(mModel);

    // Register intent receivers
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_LOCALE_CHANGED);
    filter.addAction(SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED);
    // For handling managed profiles
    filter.addAction(LauncherAppsCompat.ACTION_MANAGED_PROFILE_ADDED);
    filter.addAction(LauncherAppsCompat.ACTION_MANAGED_PROFILE_REMOVED);
    filter.addAction(LauncherAppsCompat.ACTION_MANAGED_PROFILE_AVAILABLE);
    filter.addAction(LauncherAppsCompat.ACTION_MANAGED_PROFILE_UNAVAILABLE);

    sContext.registerReceiver(mModel, filter);
    ...
}         

LauncherAppsCompat里添加了一個應用變化的回調,由LauncherModel實現接口,及時的響應數據變化。LauncherAppsCompat是獲取所有應用,監聽應用變化的一個抽象,Android 5.0前后的版本獲取方式不一樣了,這就是Launcher良好適配性的體現了。

        LauncherAppsCompat.getInstance(sContext).addOnAppsChangedCallback(mModel);

Android 5.0以前的監聽

private void registerForPackageIntents() {
    IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    filter.addDataScheme("package");
    mContext.registerReceiver(mPackageMonitor, filter);
    filter = new IntentFilter();
    filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
    filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
    mContext.registerReceiver(mPackageMonitor, filter);
}

Android5.0后的監聽

import android.content.pm.LauncherApps;

protected LauncherApps mLauncherApps;

public void addOnAppsChangedCallback(LauncherAppsCompat.OnAppsChangedCallbackCompat callback) {
    WrappedCallback wrappedCallback = new WrappedCallback(callback);
    synchronized (mCallbacks) {
        mCallbacks.put(callback, wrappedCallback);
    }
    mLauncherApps.registerCallback(wrappedCallback);
}

除了TestingUtils,應用變化監聽外,初始化兩個核心對象IconCache,LauncherModel。LauncherModel添加了設備變更,用戶信息變更的廣播,這是因為當用戶修改設備信息如語言,區域,用戶信息等,LauncherModel會刷新數據,改變圖標,標題等信息。
LauncherAppState的初始化到這里基本上就完成了。

DeviceProfile,InvariantDeviceProfile,Launcher的配置

我們繼續看,下一步

LauncherAppState app = LauncherAppState.getInstance();

// Load configuration-specific DeviceProfile
mDeviceProfile = getResources().getConfiguration().orientation
        == Configuration.ORIENTATION_LANDSCAPE ?
        app.getInvariantDeviceProfile().landscapeProfile
        : app.getInvariantDeviceProfile().portraitProfile;

通過Configuration獲取橫屏配置landscapeProfile 或者portraitProfile豎屏配置

DeviceProfile

DeviceProfile的數據都是來自InvariantDeviceProfile,封裝一些工具方法,我們直接看重點InvariantDeviceProfile

InvariantDeviceProfile

InvariantDeviceProfile的初始化是在LauncherAppState構造里new出來的,調用的是

InvariantDeviceProfile(Context context) {
    ...
    numRows = closestProfile.numRows;
    numColumns = closestProfile.numColumns;
    numHotseatIcons = closestProfile.numHotseatIcons;
    hotseatAllAppsRank = (int) (numHotseatIcons / 2);
    defaultLayoutId = closestProfile.defaultLayoutId;
    numFolderRows = closestProfile.numFolderRows;
    numFolderColumns = closestProfile.numFolderColumns;
    minAllAppsPredictionColumns = closestProfile.minAllAppsPredictionColumns;

    iconSize = interpolatedDeviceProfileOut.iconSize;
    iconBitmapSize = Utilities.pxFromDp(iconSize, dm);
    iconTextSize = interpolatedDeviceProfileOut.iconTextSize;
    hotseatIconSize = interpolatedDeviceProfileOut.hotseatIconSize;
    fillResIconDpi = getLauncherIconDensity(iconBitmapSize);

    // If the partner customization apk contains any grid overrides, apply them
    // Supported overrides: numRows, numColumns, iconSize
    applyPartnerDeviceProfileOverrides(context, dm);

    Point realSize = new Point();
    display.getRealSize(realSize);
    // The real size never changes. smallSide and largeSide will remain the
    // same in any orientation.
    int smallSide = Math.min(realSize.x, realSize.y);
    int largeSide = Math.max(realSize.x, realSize.y);

    landscapeProfile = new DeviceProfile(context, this, smallestSize, largestSize,
            largeSide, smallSide, true /* isLandscape */);
    portraitProfile = new DeviceProfile(context, this, smallestSize, largestSize,
            smallSide, largeSide, false /* isLandscape */);
}

可以看到,通過closestProfile和interpolatedDeviceProfileOut拿到了一系列配置項,如桌面的行,列,Hotseat(桌面底部固定的應用欄)的個數,Hotseat所有應用的位置,布局id,文件夾的行列,圖標的大小等等。之后再將這些信息new出我們的DeviceProfile對象。
那問題來了,closestProfile和interpolatedDeviceProfileOut是什么??怎么計算出來的?

...
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
display.getMetrics(dm);

Point smallestSize = new Point();
Point largestSize = new Point();
display.getCurrentSizeRange(smallestSize, largestSize);

// This guarantees that width < height
minWidthDps = Utilities.dpiFromPx(Math.min(smallestSize.x, smallestSize.y), dm);
minHeightDps = Utilities.dpiFromPx(Math.min(largestSize.x, largestSize.y), dm);

ArrayList<InvariantDeviceProfile> closestProfiles =
        findClosestDeviceProfiles(minWidthDps, minHeightDps, getPredefinedDeviceProfiles());
InvariantDeviceProfile interpolatedDeviceProfileOut =
        invDistWeightedInterpolate(minWidthDps,  minHeightDps, closestProfiles);
...

可以發現,通過設備的寬高等信息,從各種分辨率的DeviceProfiles列表中找到最合適的配置信息,查找的方法如下,根據
設備的寬高跟列表里的的最小寬高差值的平方根從小到大排序,第一個就是我們期望的配置

/**
 * Returns the closest device profiles ordered by closeness to the specified width and height
 */
// Package private visibility for testing.
ArrayList<InvariantDeviceProfile> findClosestDeviceProfiles(
        final float width, final float height, ArrayList<InvariantDeviceProfile> points) {

    // Sort the profiles by their closeness to the dimensions
    ArrayList<InvariantDeviceProfile> pointsByNearness = points;
    Collections.sort(pointsByNearness, new Comparator<InvariantDeviceProfile>() {
        public int compare(InvariantDeviceProfile a, InvariantDeviceProfile b) {
            return Float.compare(dist(width, height, a.minWidthDps, a.minHeightDps),
                    dist(width, height, b.minWidthDps, b.minHeightDps));
        }
    });

    return pointsByNearness;
}

@Thunk float dist(float x0, float y0, float x1, float y1) {
    return (float) Math.hypot(x1 - x0, y1 - y0);
}

配置好的InvariantDeviceProfile列表信息如下,構造參數依次是,
配置名稱,寬高,行數,列數,文件夾行數列數,圖標大小,圖標文本大小
hotseat配置資源文件,hotseat圖標大小,默認頁的資源文件
故,當我們有新機型沒有適配,就可以在這里修改或新增配置

ArrayList<InvariantDeviceProfile> getPredefinedDeviceProfiles() {
    ArrayList<InvariantDeviceProfile> predefinedDeviceProfiles = new ArrayList<>();
    // width, height, #rows, #columns, #folder rows, #folder columns,
    // iconSize, iconTextSize, #hotseat, #hotseatIconSize, defaultLayoutId.
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Super Short Stubby",
            255, 300,     2, 3, 2, 3, 3, 48, 13, 3, 48, R.xml.default_workspace_3x3));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Shorter Stubby",
            255, 400,     3, 3, 3, 3, 3, 48, 13, 3, 48, R.xml.default_workspace_3x3));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Short Stubby",
            275, 420,     3, 4, 3, 4, 4, 48, 13, 5, 48, R.xml.default_workspace_4x4));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Stubby",
            255, 450,     3, 4, 3, 4, 4, 48, 13, 5, 48, R.xml.default_workspace_4x4));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Nexus S",
            296, 491.33f, 4, 4, 4, 4, 4, 48, 13, 5, 48, R.xml.default_workspace_4x4));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Nexus 4",
            359, 567,     4, 4, 4, 4, 4, DEFAULT_ICON_SIZE_DP, 13, 5, 56, R.xml.default_workspace_4x4));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Nexus 5",
            335, 567,     5, 4, 5, 4, 4, DEFAULT_ICON_SIZE_DP, 13, 5, 56, R.xml.default_workspace_5x4_no_all_apps));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Large Phone",
            406, 694,     5, 5, 4, 4, 4, 64, 14.4f,  5, 56, R.xml.default_workspace_5x5));
    // The tablet profile is odd in that the landscape orientation
    // also includes the nav bar on the side
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Nexus 7",
            575, 904,     5, 6, 4, 5, 4, 72, 14.4f,  7, 60, R.xml.default_workspace_5x6));
    // Larger tablet profiles always have system bars on the top & bottom
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("Nexus 10",
            727, 1207,    5, 6, 4, 5, 4, 76, 14.4f,  7, 76, R.xml.default_workspace_5x6));
    predefinedDeviceProfiles.add(new InvariantDeviceProfile("20-inch Tablet",
            1527, 2527,   7, 7, 6, 6, 4, 100, 20,  7, 72, R.xml.default_workspace_5x6));
    return predefinedDeviceProfiles;
}

Launcher的配置初始化到這里基本上就完成了。

還有一些其他的對象的初始化,包括workspace狀態變化的動畫加載控制LauncherStateTransitionAnimation, 應用組件的管理器AppWidgetManagerCompat, 處理組件長按事件的ViewLauncherAppWidgetHost,因為在Launcher的初始化流程里不是特別需要,故后文有機會再做介紹。

LauncherModel加載應用信息

整個流程里比較復雜的就是LauncherModel加載應用了, 在onCreate里

    mModel = app.setLauncher(this);
    

LauncherAppState里調用了LauncherModel的初始化方法 initialize,參數是Launcher

  LauncherModel setLauncher(Launcher launcher) {
        getLauncherProvider().setLauncherProviderChangeListener(launcher);
        mModel.initialize(launcher);
        mAccessibilityDelegate = ((launcher != null) && Utilities.ATLEAST_LOLLIPOP) ?
            new LauncherAccessibilityDelegate(launcher) : null;
        return mModel;
    }

LauncherModel的initialize參數是LauncherModel.Callbacks,Launcher里實現了LauncherModel.Callbacks的一系列接口用于綁定獲取到的應用信息,文件夾信息,屏幕信息等等


 public void initialize(Callbacks callbacks) {
        synchronized (mLock) {
            // Disconnect any of the callbacks and drawables associated with ItemInfos on the
            // workspace to prevent leaking Launcher activities on orientation change.
            unbindItemInfosAndClearQueuedBindRunnables();
            mCallbacks = new WeakReference<Callbacks>(callbacks);
        }
    }

在加載數據之前先清除正在運行的線程DeferredBindRunnables,清除DeferredHandler里等待執行的任務
,并且將所有ItemInfo unbind

/** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
void unbindWorkspaceItemsOnMainThread() {
    // Ensure that we don't use the same workspace items data structure on the main thread
    // by making a copy of workspace items first.
    final ArrayList<ItemInfo> tmpItems = new ArrayList<ItemInfo>();
    synchronized (sBgLock) {
        tmpItems.addAll(sBgWorkspaceItems);
        tmpItems.addAll(sBgAppWidgets);
    }
    Runnable r = new Runnable() {
            @Override
            public void run() {
                for (ItemInfo item : tmpItems) {
                    item.unbind();
                }
            }
        };
    runOnMainThread(r);
}

接著我們才看到真正開始加載數據了,onCreate里的LauncherModel調用startLoader,創建線程加載數據


        ...        
        if (!mRestoring) {
            if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) {
                // If the user leaves launcher, then we should just load items asynchronously when
                // they return.
                mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);
            } else {
                // We only load the page synchronously if the user rotates (or triggers a
                // configuration change) while launcher is in the foreground
                mModel.startLoader(mWorkspace.getRestorePage());
            }
        }
        ...
        

當第一次打開時,會調用 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE),停止舊的Loader任務,stopLoaderLocked,然后new出一個LoaderTask(mApp.getContext(), loadFlags) Runnable,通過Handler sworker post出去,開始加載任務

public void startLoader(int synchronousBindPage) {
    startLoader(synchronousBindPage, LOADER_FLAG_NONE);
}

public void startLoader(int synchronousBindPage, int loadFlags) {
        // Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
        InstallShortcutReceiver.enableInstallQueue();
        synchronized (mLock) {
            // Clear any deferred bind-runnables from the synchronized load process
            // We must do this before any loading/binding is scheduled below.
            synchronized (mDeferredBindRunnables) {
                mDeferredBindRunnables.clear();
            }

            // Don't bother to start the thread if we know it's not going to do anything
            if (mCallbacks != null && mCallbacks.get() != null) {
                // If there is already one running, tell it to stop.
                stopLoaderLocked();
                mLoaderTask = new LoaderTask(mApp.getContext(), loadFlags);
                if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
                        && mAllAppsLoaded && mWorkspaceLoaded && !mIsLoaderTaskRunning) {
                    mLoaderTask.runBindSynchronousPage(synchronousBindPage);
                } else {
                    sWorkerThread.setPriority(Thread.NORM_PRIORITY);
                    sWorker.post(mLoaderTask);
                }
            }
        }
    }


開始加載應用信息的任務后,由于后續的篇幅比較長,請看下一篇文章的詳細介紹。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,837評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,196評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,688評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,654評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,456評論 6 406
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,955評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,044評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,195評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,725評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,608評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,802評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,318評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,048評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,422評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,673評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,424評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,762評論 2 372

推薦閱讀更多精彩內容