SystemUI之Qs Tile加载流程

引言

Quick Settings行内人简称qs,是SystemUI必不可少的一部分。它主要负责打开关闭各个系统的功能模块,如wifi、蓝牙、手电筒等。


SystemUI之Qs Tile加载流程_第1张图片
qs.png

从图中可以看出,每一个系统功能都对应这一个按钮,而这个按钮的学名就是Tile。

正文

单个Tile的加载流程

SystemUI是如何加载每个Tile的呢?在Statusbar初始化的时候,在makeStatusbarBarView()中对QsTile进行了初始化:

protected void makeStatusBarView() {
        ......

        // Set up the quick settings tile panel
        View container = mStatusBarWindow.findViewById(R.id.qs_frame);
        if (container != null) {
            FragmentHostManager fragmentHostManager = FragmentHostManager.get(container);
            ExtensionFragmentListener.attachExtensonToFragment(container, QS.TAG, R.id.qs_frame,
                    Dependency.get(ExtensionController.class)
                            .newExtension(QS.class)
                            .withPlugin(QS.class)
                            .withFeature(PackageManager.FEATURE_AUTOMOTIVE, CarQSFragment::new)
                            .withDefault(QSFragment::new)
                            .build());
            final QSTileHost qsh = SystemUIFactory.getInstance().createQSTileHost(mContext, this,
                    mIconController);
            mBrightnessMirrorController = new BrightnessMirrorController(mStatusBarWindow,
                    (visible) -> {
                        mBrightnessMirrorVisible = visible;
                        updateScrimController();
                    });
            fragmentHostManager.addTagListener(QS.TAG, (tag, f) -> {
                QS qs = (QS) f;
                if (qs instanceof QSFragment) {
                    ((QSFragment) qs).setHost(qsh);
                    mQSPanel = ((QSFragment) qs).getQsPanel();
                    mQSPanel.setBrightnessMirror(mBrightnessMirrorController);
                    mKeyguardStatusBar.setQSPanel(mQSPanel);
                }
            });
        }
        ......
    }

通过初始化QsTileHost,进行QsTile的加载。在QsTileHost初始化的时候,增加Tunable监听:

public QSTileHost(Context context, StatusBar statusBar,
            StatusBarIconController iconController) {
        mIconController = iconController;
        mContext = context;
        mStatusBar = statusBar;

        mServices = new TileServices(this, Dependency.get(Dependency.BG_LOOPER));

        mQsFactories.add(new QSFactoryImpl(this));
        Dependency.get(PluginManager.class).addPluginListener(this, QSFactory.class, true);

        Dependency.get(TunerService.class).addTunable(this, TILES_SETTING);
        // AutoTileManager can modify mTiles so make sure mTiles has already been initialized.
        mAutoTiles = new AutoTileManager(context, this);
    }

这里的TunerSerivce的作用是注册对字段"sysui_qs_tiles"的系统数据库监听:

private void addTunable(Tunable tunable, String key) {
        if (!mTunableLookup.containsKey(key)) {
            mTunableLookup.put(key, new ArraySet());
        }
        mTunableLookup.get(key).add(tunable);
        if (LeakDetector.ENABLED) {
            mTunables.add(tunable);
            Dependency.get(LeakDetector.class).trackCollection(mTunables, "TunerService.mTunables");
        }
        Uri uri = Settings.Secure.getUriFor(key);
        if (!mListeningUris.containsKey(uri)) {
            mListeningUris.put(uri, key);
            mContentResolver.registerContentObserver(uri, false, mObserver, mCurrentUser);
        }
        // Send the first state.
        String value = Settings.Secure.getStringForUser(mContentResolver, key, mCurrentUser);
        tunable.onTuningChanged(key, value);
    }

通过addTunable触发QsTileHost中onTuningChanged:

@Override
    public void onTuningChanged(String key, String newValue) {
        if (!TILES_SETTING.equals(key)) {
            return;
        }
        if (DEBUG) Log.d(TAG, "Recreating tiles");
        if (newValue == null && UserManager.isDeviceInDemoMode(mContext)) {
            newValue = mContext.getResources().getString(R.string.quick_settings_tiles_retail_mode);
        }
        final List tileSpecs = loadTileSpecs(mContext, newValue);
        int currentUser = ActivityManager.getCurrentUser();
        if (tileSpecs.equals(mTileSpecs) && currentUser == mCurrentUser) return;
        mTiles.entrySet().stream().filter(tile -> !tileSpecs.contains(tile.getKey())).forEach(
                tile -> {
                    if (DEBUG) Log.d(TAG, "Destroying tile: " + tile.getKey());
                    tile.getValue().destroy();
                });
        final LinkedHashMap newTiles = new LinkedHashMap<>();
        for (String tileSpec : tileSpecs) {
            QSTile tile = mTiles.get(tileSpec);
            if (tile != null && (!(tile instanceof CustomTile)
                    || ((CustomTile) tile).getUser() == currentUser)) {
                if (tile.isAvailable()) {
                    if (DEBUG) Log.d(TAG, "Adding " + tile);
                    tile.removeCallbacks();
                    if (!(tile instanceof CustomTile) && mCurrentUser != currentUser) {
                        tile.userSwitch(currentUser);
                    }
                    newTiles.put(tileSpec, tile);
                } else {
                    tile.destroy();
                }
            } else {
                if (DEBUG) Log.d(TAG, "Creating tile: " + tileSpec);
                try {
                    tile = createTile(tileSpec);
                    if (tile != null) {
                        if (tile.isAvailable()) {
                            tile.setTileSpec(tileSpec);
                            newTiles.put(tileSpec, tile);
                        } else {
                            tile.destroy();
                        }
                    }
                } catch (Throwable t) {
                    Log.w(TAG, "Error creating tile for spec: " + tileSpec, t);
                }
            }
        }
        mCurrentUser = currentUser;
        mTileSpecs.clear();
        mTileSpecs.addAll(tileSpecs);
        mTiles.clear();
        mTiles.putAll(newTiles);
        for (int i = 0; i < mCallbacks.size(); i++) {
            mCallbacks.get(i).onTilesChanged();
        }
    }

以上步骤进行了读取配置,并creatTile的操作。通过loadTileSpecs()获取到需要createTile的list:

protected List loadTileSpecs(Context context, String tileList) {
        final Resources res = context.getResources();
        String defaultTileList = res.getString(R.string.quick_settings_tiles_default);
        if (tileList == null) {
            tileList = res.getString(R.string.quick_settings_tiles);
            if (DEBUG) Log.d(TAG, "Loaded tile specs from config: " + tileList);
        } else {
            if (DEBUG) Log.d(TAG, "Loaded tile specs from setting: " + tileList);
        }
        final ArrayList tiles = new ArrayList();
        boolean addedDefault = false;
        for (String tile : tileList.split(",")) {
            tile = tile.trim();
            if (tile.isEmpty()) continue;
            if (tile.equals("default")) {
                if (!addedDefault) {
                    tiles.addAll(Arrays.asList(defaultTileList.split(",")));
                    addedDefault = true;
                }
            } else {
                tiles.add(tile);
            }
        }
        return tiles;
    }

通过"quick_settings_tiles_default"进入默认tile的配置,这里的tile list不包括可编辑的。获取到list之后,通过creatTile()进行创建:

public QSTile createTile(String tileSpec) {
        for (int i = 0; i < mQsFactories.size(); i++) {
            QSTile t = mQsFactories.get(i).createTile(tileSpec);
            if (t != null) {
                return t;
            }
        }
        return null;
    }

这里通过循环,在QsFactoryImpl中进行tile的创建:

public QSTile createTile(String tileSpec) {
        QSTileImpl tile = createTileInternal(tileSpec);
        if (tile != null) {
            tile.handleStale(); // Tile was just created, must be stale.
        }
        return tile;
    }

private QSTileImpl createTileInternal(String tileSpec) {
        switch (tileSpec) {
            case "wifi":
                return new WifiTile(mHost);
            case "bt":
                return new BluetoothTile(mHost);
            case "cell":
                return new CellularTile(mHost);
            case "dnd":
                return new DndTile(mHost);
            case "inversion":
                return new ColorInversionTile(mHost);
            case "airplane":
                return new AirplaneModeTile(mHost);
            case "work":
                return new WorkModeTile(mHost);
            case "rotation":
                return new RotationLockTile(mHost);
            case "flashlight":
                return new FlashlightTile(mHost);
            case "location":
                return new LocationTile(mHost);
            case "cast":
                return new CastTile(mHost);
            case "hotspot":
                return new HotspotTile(mHost);
            case "user":
                return new UserTile(mHost);
            case "battery":
                return new BatterySaverTile(mHost);
            case "saver":
                return new DataSaverTile(mHost);
            case "night":
                return new NightDisplayTile(mHost);
            case "nfc":
                return new NfcTile(mHost);
        }

        // Intent tiles.
        if (tileSpec.startsWith(IntentTile.PREFIX)) return IntentTile.create(mHost, tileSpec);
        if (tileSpec.startsWith(CustomTile.PREFIX)) return CustomTile.create(mHost, tileSpec);

        // Debug tiles.
        if (Build.IS_DEBUGGABLE) {
            if (tileSpec.equals(GarbageMonitor.MemoryTile.TILE_SPEC)) {
                return new GarbageMonitor.MemoryTile(mHost);
            }
        }

        // Broken tiles.
        Log.w(TAG, "Bad tile spec: " + tileSpec);
        return null;
    }

根据tileSpec进行对应tile的初始化。

编辑区Tile加载流程

当用户点击qs区域的编辑按钮时,可以看到一个这样的界面:


SystemUI之Qs Tile加载流程_第2张图片
qs_edit.png
SystemUI之Qs Tile加载流程_第3张图片
qs_edit2.png

从图中可以看出,进入qs编辑模式之后,会出现更多tile,并且可以拖动到上方供用户平时下拉后直接使用,或者将不常用的放到待选区域。这里从UI上可以看出待选区域由两部分组成,一部分是SystemUI内部的Tile,而类似google Nearby这种Tile则是第三应用自己注册的Tile。接下来,就分析一下这些Tile是如何加载的?
当进入编辑模式之后,QsCustomer会对tile有一个query操作,由TileQueryHelper实现:

public void queryTiles(QSTileHost host) {
        mTiles.clear();
        mSpecs.clear();
        mFinished = false;
        // Enqueue jobs to fetch every system tile and then ever package tile.
        addStockTiles(host);
        addPackageTiles(host);
    }

从代码中也可以看出,加载Tile分成了StockTiles和PackageTiles,分别代表SystemUI内置Tile和第三注册Tile,先来看下内置Tile:

private void addStockTiles(QSTileHost host) {
        String possible = mContext.getString(R.string.quick_settings_tiles_stock);
        final ArrayList possibleTiles = new ArrayList<>();
        possibleTiles.addAll(Arrays.asList(possible.split(",")));
        if (Build.IS_DEBUGGABLE) {
            possibleTiles.add(GarbageMonitor.MemoryTile.TILE_SPEC);
        }
        final ArrayList tilesToAdd = new ArrayList<>();
        for (String spec : possibleTiles) {
            final QSTile tile = host.createTile(spec);
            if (tile == null) {
                continue;
            } else if (!tile.isAvailable()) {
                tile.destroy();
                continue;
            }
            tile.setListening(this, true);
            tile.clearState();
            tile.refreshState();
            tile.setListening(this, false);
            tile.setTileSpec(spec);
            tilesToAdd.add(tile);
        }

        mBgHandler.post(() -> {
            for (QSTile tile : tilesToAdd) {
                final QSTile.State state = tile.getState().copy();
                // Ignore the current state and get the generic label instead.
                state.label = tile.getTileLabel();
                tile.destroy();
                addTile(tile.getTileSpec(), null, state, true);
            }
            notifyTilesChanged(false);
        });
    }

"quick_settings_tiles_stock"对应的就是SystemUI中可加载的所有Tile,如果希望客制化也可以在此处进行修改。接下来,再看一下如何加载第三方Tile(如Nearby):

private void addPackageTiles(final QSTileHost host) {
        mBgHandler.post(() -> {
            Collection params = host.getTiles();
            PackageManager pm = mContext.getPackageManager();
            List services = pm.queryIntentServicesAsUser(
                    new Intent(TileService.ACTION_QS_TILE), 0, ActivityManager.getCurrentUser());
            String stockTiles = mContext.getString(R.string.quick_settings_tiles_stock);

            for (ResolveInfo info : services) {
                String packageName = info.serviceInfo.packageName;
                ComponentName componentName = new ComponentName(packageName, info.serviceInfo.name);

                // Don't include apps that are a part of the default tile set.
                if (stockTiles.contains(componentName.flattenToString())) {
                    continue;
                }

                final CharSequence appLabel = info.serviceInfo.applicationInfo.loadLabel(pm);
                String spec = CustomTile.toSpec(componentName);
                State state = getState(params, spec);
                if (state != null) {
                    addTile(spec, appLabel, state, false);
                    continue;
                }
                if (info.serviceInfo.icon == 0 && info.serviceInfo.applicationInfo.icon == 0) {
                    continue;
                }
                Drawable icon = info.serviceInfo.loadIcon(pm);
                if (!permission.BIND_QUICK_SETTINGS_TILE.equals(info.serviceInfo.permission)) {
                    continue;
                }
                if (icon == null) {
                    continue;
                }
                icon.mutate();
                icon.setTint(mContext.getColor(android.R.color.white));
                CharSequence label = info.serviceInfo.loadLabel(pm);
                addTile(spec, icon, label != null ? label.toString() : "null", appLabel);
            }

            notifyTilesChanged(true);
        });
    }

从代码中不难看出,通过PackageManager来query带有“TileService.ACTION_QS_TILE”的Intent的应用,获取到它们的resolveinfo获取第三方注册的Tile的信息,如Tile的名称、icon、应用名称等。

到这里,Qs Tile加载的数据流程已经讲完,后面有时间再讲一下UI的加载流程。如有什么问题欢迎指正。

本文章已经独家授权ApeClub公众号使用。

你可能感兴趣的:(SystemUI之Qs Tile加载流程)