Android开发android

Android 13 Launcher 源码分析(一)

2023-03-07  本文已影响0人  孤街酒客0911

学习笔记:


一、Launcher 简介

Launcher 是 Android 系统不可缺少的部分,我们通常称之为 Android 系统的桌面,它在 Android 系统中起着重要的作用。

二、Launcher 结构

在 Launcher 中主要有两大组件:

UI组件.png 桌面组件.png
三、launcher 启动

参考Android系统开机到Launcher启动流程分析Android 10.0 launcher启动流程

四、主要文件和类
五、launcher 源码分析

launcher.java 是 launcher 主要、第一个启动的 activity,在其里面进行显示、初始化一些 View。
launcher#onCreate()

// launcher.java
    protected void onCreate(Bundle savedInstanceState) {
        // 省略部分代码......
        Object traceToken = TraceHelper.INSTANCE.beginSection(ON_CREATE_EVT,
                TraceHelper.FLAG_UI_EVENT);
        if (DEBUG_STRICT_MODE) {
            //StrictMode被称为严苛模式,google提供用来进行测试的类
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork()   // or .detectAll() for all detectable problems
                    .penaltyLog()
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects()
                    .detectLeakedClosableObjects()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());
        }

        // 省略部分代码......

        super.onCreate(savedInstanceState);

        // 单例模式,初始化LauncherAppState
        LauncherAppState app = LauncherAppState.getInstance(this);
        mOldConfig = new Configuration(getResources().getConfiguration());
         // 获取LauncherModel实例
        mModel = app.getModel();

        mRotationHelper = new RotationHelper(this);
        InvariantDeviceProfile idp = app.getInvariantDeviceProfile();
        // 初始化手机固件信息对象DeviceProfile
        initDeviceProfile(idp);
        idp.addOnChangeListener(this);
        // 获取sharedPreferences
        mSharedPrefs = Utilities.getPrefs(this);
        // 获取IconCache实例,此类主要保存图标信息
        mIconCache = app.getIconCache();
        mAccessibilityDelegate = createAccessibilityDelegate();
        // 拖拽
        mDragController = new LauncherDragController(this);
        mAllAppsController = new AllAppsTransitionController(this);
        mStateManager = new StateManager<>(this, NORMAL);

        mOnboardingPrefs = createOnboardingPrefs(mSharedPrefs);

        // 获取AppWidgetManager实例,用来管理widge
        mAppWidgetManager = new WidgetManagerHelper(this);
        mAppWidgetHost = createAppWidgetHost();
        mAppWidgetHost.startListening();

        // 设置布局
        inflateRootView(R.layout.launcher);
        // 初始化View,进行各种View的初始化事件绑定
        setupViews();
        crossFadeWithPreviousAppearance();
        mPopupDataProvider = new PopupDataProvider(this::updateNotificationDots);

        boolean internalStateHandled = ACTIVITY_TRACKER.handleCreate(this);
        if (internalStateHandled) {
            if (savedInstanceState != null) {
                // InternalStateHandler has already set the appropriate state.
                // We dont need to do anything.
                savedInstanceState.remove(RUNTIME_STATE);
            }
        }
        restoreState(savedInstanceState);
        mStateManager.reapplyState();

        if (savedInstanceState != null) {
            int[] pageIds = savedInstanceState.getIntArray(RUNTIME_STATE_CURRENT_SCREEN_IDS);
            if (pageIds != null) {
                mPagesToBindSynchronously = IntSet.wrap(pageIds);
            }
        }
        // 加载、绑定数据(这里与之前版本的 startLoader() 作用一样)
        if (!mModel.addCallbacksAndLoad(this)) {
            if (!internalStateHandled) {
                Log.d(BAD_STATE, "Launcher onCreate not binding sync, prevent drawing");
                // If we are not binding synchronously, pause drawing until initial bind complete,
                // so that the system could continue to show the device loading prompt
                mOnInitialBindListener = Boolean.FALSE::booleanValue;
            }
        }

        // For handling default keys
        setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

        setContentView(getRootView());
        if (mOnInitialBindListener != null) {
            //getRootView().getViewTreeObserver().addOnPreDrawListener(mOnInitialBindListener);
        }
        getRootView().dispatchInsets();

        // 注册屏幕关闭广播
        registerReceiver(mScreenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));

        getSystemUiController().updateUiState(SystemUiController.UI_STATE_BASE_WINDOW,
                Themes.getAttrBoolean(this, R.attr.isWorkspaceDarkText));

        if (mLauncherCallbacks != null) {
            mLauncherCallbacks.onCreate(savedInstanceState);
        }
        mOverlayManager = getDefaultOverlay();
        PluginManagerWrapper.INSTANCE.get(this).addPluginListener(this,
                LauncherOverlayPlugin.class, false /* allowedMultiple */);

        mRotationHelper.initialize();
        TraceHelper.INSTANCE.endSection(traceToken);

        mUserChangedCallbackCloseable = UserCache.INSTANCE.get(this).addUserChangeListener(
                () -> getStateManager().goToState(NORMAL));

        if (Utilities.ATLEAST_R) {
            getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        }
        setTitle(R.string.home_screen);
    }

从代码中可以看出,首先调用了 LauncherAppState.getInstance(this) 来初始化一个单例对象 ,而LauncherAppState 里面保存了一些比较常用的对象,方便其他地方通过单例来获取,比如 IconCache、LauncherModel 等;并且注册了广播监听器和 ContentObserver ;设置布局 launcher.xml,调用 setupViews() 又是一些 View 的初始化,设置回调监听等。

总结一下 onCreate() 的工作:初始化对象、加载布局、注册一些事件监听、以及开启数据加载。

上一篇 下一篇

猜你喜欢

热点阅读