Android 11 Settings动态加载之快霸是如何被加载的

设置项列表的内容通过静态配置+动态添加的方式获取。本文以MTK平台的快霸为例探讨如何进行动态加载。

一,解析动态加载项

每个页面都有自己特定的动态加载项,那么每个页面如果获取动态加载项呢?

TopLevelSettings为例继承自DashboardFragment

public abstract class DashboardFragment extends SettingsPreferenceFragment
        implements SettingsBaseActivity.CategoryListener, Indexable,
        PreferenceGroup.OnExpandButtonClickListener,
        BasePreferenceController.UiBlockListener {
        
    
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        ...
        // 1,刷新所有Preference
        refreshAllPreferences(getLogTag());
        ...
    }    
    
    /**
     * Refresh all preference items, including both static prefs from xml, and dynamic items from
     * DashboardCategory.
     */
    private void refreshAllPreferences(final String tag) {
        ...
        // Add resource based tiles.
        // 展示静态配置的Preference项
        displayResourceTiles();
        
        // 2,展示动态加载项
        refreshDashboardTiles(tag);
        ...
    }
    
    
    /**
     * Refresh preference items backed by DashboardCategory.
     */
    private void refreshDashboardTiles(final String tag) {
        final PreferenceScreen screen = getPreferenceScreen();
        // 3,获取动态加载项
        final DashboardCategory category =
                mDashboardFeatureProvider.getTilesForCategory(getCategoryKey());
        ...           
    }
}

动态加载项通过mDashboardFeatureProvider.getTilesForCategory()来获取,需要传入一个key值作为参数。

1.1 key的来历

首先看一下这个key是怎么来的呢?通过调用getCategoryKey()获得

public String getCategoryKey() {
    return DashboardFragmentRegistry.PARENT_TO_CATEGORY_KEY_MAP.get(getClass().getName());
}

DashboardFragmentRegistry.PARENT_TO_CATEGORY_KEY_MAP是一个静态变量,在类的静态代码块中添加了数据:

public class DashboardFragmentRegistry {

    /**
     * Map from parent fragment to category key. The parent fragment hosts child with
     * category_key.
     */
    public static final Map PARENT_TO_CATEGORY_KEY_MAP;
    ...

    static {
        PARENT_TO_CATEGORY_KEY_MAP = new ArrayMap<>();
        PARENT_TO_CATEGORY_KEY_MAP.put(TopLevelSettings.class.getName(),
                CategoryKey.CATEGORY_HOMEPAGE);
        ...
    }

再来看看CategoryKey.CATEGORY_HOMEPAGE

public final class CategoryKey {

    // Activities in this category shows up in Settings homepage.
    public static final String CATEGORY_HOMEPAGE = "com.android.settings.category.ia.homepage";
    ...
}

因此TopLevelSettings类查找的是com.android.settings.category.ia.homepage

在来看看快霸中的manifest:


    
        
        
        
    
    
        
    

    
    

其中配置了key为com.android.settings.category,value为com.android.settings.category.ia.homepagemeta-data。因此在首页动态加载时会加载快霸。

1.2 根据key值动态加载

DashboardFeatureProvider的实现类是DashboardFeatureProviderImpl, 它实现了getTilesForCategory(), 最终还是通过CategoryManager来获取Category。

public class DashboardFeatureProviderImpl implements DashboardFeatureProvider {

    ...
    private final CategoryManager mCategoryManager;
    ...
    
    public DashboardFeatureProviderImpl(Context context) {
        ...
        // CategoryManager是一个单例
        mCategoryManager = CategoryManager.get(context);
        ...
    }

    @Override
    public DashboardCategory getTilesForCategory(String key) {
        // 查找动态项
        return mCategoryManager.getTilesByCategory(mContext, key);
    }

在CategoryManager中首先进行加载,然后保存在mCategoryByKeyMap中,最后通过key值获取对应的加载项

public synchronized DashboardCategory getTilesByCategory(Context context, String categoryKey) {
    // 1,加载
    tryInitCategories(context);
    // 2,读取
    return mCategoryByKeyMap.get(categoryKey);
}

private synchronized void tryInitCategories(Context context) {
    // Keep cached tiles by default. The cache is only invalidated when InterestingConfigChange
    // happens.
    tryInitCategories(context, false /* forceClearCache */);
}


private synchronized void tryInitCategories(Context context, boolean forceClearCache) {
    if (mCategories == null) {
        if (forceClearCache) {
            mTileByComponentCache.clear();
        }
        mCategoryByKeyMap.clear();
        // 加载
        mCategories = TileUtils.getCategories(context, mTileByComponentCache);
        for (DashboardCategory category : mCategories) {
            // 根据不同的key保存在map中
            mCategoryByKeyMap.put(category.key, category);
        }
        backwardCompatCleanupForCategory(mTileByComponentCache, mCategoryByKeyMap);
        // 排序
        sortCategories(context, mCategoryByKeyMap);
        // 过滤重复
        filterDuplicateTiles(mCategoryByKeyMap);
    }
}

其关键代码为TileUtils.getCategories(context, mTileByComponentCache)

1.2.1

其中TileUtils位于SettingsLib中,包名为:com.android.settingslib.drawer.TileUtils,代码如下:

/**
 * Build a list of DashboardCategory.
 */
public static List getCategories(Context context,
        Map, Tile> cache) {
    final long startTime = System.currentTimeMillis();
    final boolean setup =
            Global.getInt(context.getContentResolver(), Global.DEVICE_PROVISIONED, 0) != 0;
    // 保存加载到的tile
    final ArrayList tiles = new ArrayList<>();
    final UserManager userManager = (UserManager) context.getSystemService(
            Context.USER_SERVICE);
    for (UserHandle user : userManager.getUserProfiles()) {
        // TODO: Needs much optimization, too many PM queries going on here.
        if (user.getIdentifier() == ActivityManager.getCurrentUser()) {
            // Only add Settings for this user.
            // 各种load
            loadTilesForAction(context, user, SETTINGS_ACTION, cache, null, tiles, true);
            loadTilesForAction(context, user, OPERATOR_SETTINGS, cache,
                    OPERATOR_DEFAULT_CATEGORY, tiles, false);
            loadTilesForAction(context, user, MANUFACTURER_SETTINGS, cache,
                    MANUFACTURER_DEFAULT_CATEGORY, tiles, false);
        }
        if (setup) {
            loadTilesForAction(context, user, EXTRA_SETTINGS_ACTION, cache, null, tiles, false);
            loadTilesForAction(context, user, IA_SETTINGS_ACTION, cache, null, tiles, false);
        }
    }

    final HashMap categoryMap = new HashMap<>();
    // 遍历加载到的tile
    for (Tile tile : tiles) {
        final String categoryKey = tile.getCategory();
        DashboardCategory category = categoryMap.get(categoryKey);
        if (category == null) {
            category = new DashboardCategory(categoryKey);

            if (category == null) {
                Log.w(LOG_TAG, "Couldn't find category " + categoryKey);
                continue;
            }
            categoryMap.put(categoryKey, category);
        }
        category.addTile(tile);
    }
    final ArrayList categories = new ArrayList<>(categoryMap.values());
    for (DashboardCategory category : categories) {
        // 排序
        category.sortTiles();
    }

    if (DEBUG_TIMING) {
        Log.d(LOG_TAG, "getCategories took "
                + (System.currentTimeMillis() - startTime) + " ms");
    }
    return categories;
}

注意上面定义的final ArrayList tiles = new ArrayList<>(); 这个List被传到后面的几个方法中,最终将加载到的内容放入其中。

1.2.2

根据不同action进行加载

static void loadTilesForAction(Context context,
        UserHandle user, String action, Map, Tile> addedCache,
        String defaultCategory, List outTiles, boolean requireSettings) {
    final Intent intent = new Intent(action);
    if (requireSettings) {
        intent.setPackage(SETTING_PKG);
    }
    // 分两种情况
    loadActivityTiles(context, user, addedCache, defaultCategory, outTiles, intent);
    loadProviderTiles(context, user, addedCache, defaultCategory, outTiles, intent);
}
1.2.3

根据PackageManager 获取应用的配置文件信息。

private static void loadActivityTiles(Context context,
        UserHandle user, Map, Tile> addedCache,
        String defaultCategory, List outTiles, Intent intent) {
    final PackageManager pm = context.getPackageManager();
    final List results = pm.queryIntentActivitiesAsUser(intent,
            PackageManager.GET_META_DATA, user.getIdentifier());
    for (ResolveInfo resolved : results) {
        if (!resolved.system) {
            // Do not allow any app to add to settings, only system ones.
            continue;
        }
        final ActivityInfo activityInfo = resolved.activityInfo;
        final Bundle metaData = activityInfo.metaData;
        // 加载tile
        loadTile(user, addedCache, defaultCategory, outTiles, intent, metaData, activityInfo);
    }
}

private static void loadProviderTiles(Context context,
        UserHandle user, Map, Tile> addedCache,
        String defaultCategory, List outTiles, Intent intent) {
    final PackageManager pm = context.getPackageManager();
    final List results = pm.queryIntentContentProvidersAsUser(intent,
            0 /* flags */, user.getIdentifier());
    for (ResolveInfo resolved : results) {
        if (!resolved.system) {
            // Do not allow any app to add to settings, only system ones.
            continue;
        }
        final ProviderInfo providerInfo = resolved.providerInfo;
        final List switchData = getSwitchDataFromProvider(context,
                providerInfo.authority);
        if (switchData == null || switchData.isEmpty()) {
            continue;
        }
        for (Bundle metaData : switchData) {
            // 加载tile
            loadTile(user, addedCache, defaultCategory, outTiles, intent, metaData,
                    providerInfo);
        }
    }
}
1.2.4

加载到的结果放入outTiles中,也就是前面定义的List中。

private static void loadTile(UserHandle user, Map, Tile> addedCache,
        String defaultCategory, List outTiles, Intent intent, Bundle metaData,
        ComponentInfo componentInfo) {
    String categoryKey = defaultCategory;
    // Load category
    if ((metaData == null || !metaData.containsKey(EXTRA_CATEGORY_KEY))
            && categoryKey == null) {
        Log.w(LOG_TAG, "Found " + componentInfo.name + " for intent "
                + intent + " missing metadata "
                + (metaData == null ? "" : EXTRA_CATEGORY_KEY));
        return;
    } else {
        categoryKey = metaData.getString(EXTRA_CATEGORY_KEY);
    }

    final boolean isProvider = componentInfo instanceof ProviderInfo;
    final Pair key = isProvider
            ? new Pair<>(((ProviderInfo) componentInfo).authority,
                    metaData.getString(META_DATA_PREFERENCE_KEYHINT))
            : new Pair<>(componentInfo.packageName, componentInfo.name);
    Tile tile = addedCache.get(key);
    if (tile == null) {
        tile = isProvider
                ? new ProviderTile((ProviderInfo) componentInfo, categoryKey, metaData)
                : new ActivityTile((ActivityInfo) componentInfo, categoryKey);
        addedCache.put(key, tile);
    } else {
        tile.setMetaData(metaData);
    }

    if (!tile.userHandle.contains(user)) {
        tile.userHandle.add(user);
    }
    if (!outTiles.contains(tile)) {
        outTiles.add(tile);
    }
}

到此动态项查找及获取已经完成,那么查找到后怎么显示出来的呢?

此处只是DashboardFragment中进行动态加载的逻辑,在继承自SettingsActivity的Activity中也会进行动态加载,核心逻辑是相同的,这里不做深入。

二,显示动态加载项

继续看refreshDashboardTiles()

/**
 * Refresh preference items backed by DashboardCategory.
 */
private void refreshDashboardTiles(final String tag) {
    final PreferenceScreen screen = getPreferenceScreen();

    // 加载数据
    final DashboardCategory category =
            mDashboardFeatureProvider.getTilesForCategory(getCategoryKey());
    if (category == null) {
        Log.d(tag, "NO dashboard tiles for " + tag);
        return;
    }
    final List tiles = category.getTiles();
    if (tiles == null) {
        Log.d(tag, "tile list is empty, skipping category " + category.key);
        return;
    }
    // Create a list to track which tiles are to be removed.
    final Map> remove = new ArrayMap(mDashboardTilePrefKeys);

    // Install dashboard tiles.
    final boolean forceRoundedIcons = shouldForceRoundedIcon();
    // 遍历加载项
    for (Tile tile : tiles) {
        final String key = mDashboardFeatureProvider.getDashboardKeyForTile(tile);
        if (TextUtils.isEmpty(key)) {
            Log.d(tag, "tile does not contain a key, skipping " + tile);
            continue;
        }
        if (!displayTile(tile)) {
            continue;
        }
        if (mDashboardTilePrefKeys.containsKey(key)) {
            // Have the key already, will rebind.
            final Preference preference = screen.findPreference(key);
            mDashboardFeatureProvider.bindPreferenceToTileAndGetObservers(getActivity(),
                    forceRoundedIcons, getMetricsCategory(), preference, tile, key,
                    mPlaceholderPreferenceController.getOrder());
        } else {
            // Don't have this key, add it.
            // 1,创建Preference
            final Preference pref = createPreference(tile);
            final List observers =
                    mDashboardFeatureProvider.bindPreferenceToTileAndGetObservers(getActivity(),
                            forceRoundedIcons, getMetricsCategory(), pref, tile, key,
                            mPlaceholderPreferenceController.getOrder());
            // 2,添加到screen
            screen.addPreference(pref);
            registerDynamicDataObservers(observers);
            mDashboardTilePrefKeys.put(key, observers);
        }
        remove.remove(key);
    }
    // Finally remove tiles that are gone.
    for (Map.Entry> entry : remove.entrySet()) {
        final String key = entry.getKey();
        mDashboardTilePrefKeys.remove(key);
        final Preference preference = screen.findPreference(key);
        if (preference != null) {
            screen.removePreference(preference);
        }
        unregisterDynamicDataObservers(entry.getValue());
    }
}

获取加载到的数据后进行遍历,判断当前列表中是否存在该设置项,不存在的话就创建

通过createPreference()创建Preference如下。

Preference createPreference(Tile tile) {
    return tile instanceof ProviderTile
            ? new SwitchPreference(getPrefContext())
            : tile.hasSwitch()
                    ? new MasterSwitchPreference(getPrefContext())
                    : new Preference(getPrefContext());
}

最终动态添加到screen中:

screen.addPreference(pref);

你可能感兴趣的:(Android 11 Settings动态加载之快霸是如何被加载的)