Android O设置中搜索模块数据搜集流程

Android O搜索模块的数据由各界面自己提供了,无需再为搜索单独提供数据,也无需考虑多语言翻译了,搜索模块会自动搜集各界面的字符串供用户选择,因此多语言下显示的就是对应语言的字符串,这也表明切换语言后数据需要重新搜集。

在Settings应用内,界面所属Activity或Fragment需在SearchIndexableResources中注册,并实现Indexable接口,既添加静态成员变量SEARCH_INDEX_DATA_PROVIDER,该成员变量类型为Indexable.SearchIndexProvider,根据需要实现对应的四个方法。

在用户开机或切换语言后第一次进入搜索界面时,搜索模块就会根据注册信息搜集各界面提供的数据,集成到SearchIndexableResource和SearchIndexableRaw结构中,并写入数据库,供搜索使用。

流程如下:
Android O设置中搜索模块数据搜集流程

另,若非Settings应用想要被搜索到,需要在应用内实现SearchIndexablesProvider,具体使用方法在该文件注释中有详细说明,亦可参考SettingsSearchIndexablesProvider、PhoneSearchIndexablesProvider和CellBroadcastSearchIndexableProvider的实现。

/**
 * Base class for a search indexable provider. Such provider offers data to be indexed either
 * as a reference to an XML file (like a {@link android.preference.PreferenceScreen}) or either
 * as some raw data.
 *
 * @see SearchIndexableResource
 * @see SearchIndexableData
 * @see SearchIndexablesContract
 *
 * To create a search indexables provider, extend this class, then implement the abstract methods,
 * and add it to your manifest like this:
 *
 * <pre class="prettyprint">&lt;manifest&gt;
 *    ...
 *    &lt;application&gt;
 *        ...
 *        &lt;provider
 *            android:name="com.example.MyIndexablesProvider"
 *            android:authorities="com.example.myindexablesprovider"
 *            android:exported="true"
 *            android:grantUriPermissions="true"
 *            android:permission="android.permission.READ_SEARCH_INDEXABLES"
 *            &lt;intent-filter&gt;
 *                &lt;action android:name="android.content.action.SEARCH_INDEXABLES_PROVIDER" /&gt;
 *            &lt;/intent-filter&gt;
 *        &lt;/provider&gt;
 *        ...
 *    &lt;/application&gt;
 *&lt;/manifest&gt;</pre>
 * <p>
 * When defining your provider, you must protect it with
 * {@link android.Manifest.permission#READ_SEARCH_INDEXABLES}, which is a permission only the system
 * can obtain.
 * </p>