Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 搜索 suggestions 實現搜索聯想:SearchRecentSuggestions 完整實踐

編輯:關於 Android 程式設計

所謂搜索 suggestions(搜索建議、搜索聯想),就是當用戶在搜索框裡輸入某個關鍵詞後,系統自動給出幾條包含相近關鍵詞的候選項,用戶可以直接點擊而不必輸完。

這個功能在 Android 裡有現成的解決方案,核心是 SearchRecentSuggestions 加 SearchRecentSuggestionsProvider 這對組合,不需要自己建數據庫表。

效果預覽

MainActivity:觸發搜索與清空歷史

package zhangphil.search;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button search = (Button) findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 發起搜索
                search();
            }
        });

        Button clear = (Button) findViewById(R.id.clear);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clear();
            }
        });
    }

    private void search() {
        // 向 Android 系統發起搜索請求
        this.onSearchRequested();
    }

    /**
     * onSearchRequested() 方法可以重載,也可以不重載,
     * 取決於是否需要傳遞更多參數或數據給下一步操作。
     * 通常代碼運行邏輯需要傳遞更多數據時,則重載此方法以完成更多數據的傳遞;
     * 不重載也可以,系統會啟動默認的搜索框。
     */
    @Override
    public boolean onSearchRequested() {
        Bundle bundle = new Bundle();
        bundle.putString("some_key", "some_value");
        this.startSearch("輸入搜索的關鍵詞" /* 初始化搜索框中的提示詞 */,
                true,
                bundle,
                false /* 此處若為 true,則啟動手機全局設置的搜索,比如 Google 搜索 */);
        return true;
    }

    // 清除全部歷史搜索記錄
    private void clear() {
        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                ZhangPhilSuggestionProvider.AUTHORITY,
                ZhangPhilSuggestionProvider.MODE);
        // 出於用戶隱私的考慮,給 APP 提供清除所有搜索歷史記錄的選項
        suggestions.clearHistory();
    }
}

onSearchRequested() 會觸發 Android 系統自動彈出搜索框,這是系統級組件,外觀與行為都與其他應用的搜索保持一致。

關於 startSearch() 的四個參數值得說明:初始提示詞、是否走應用級搜索、附加的 Bundle 數據、以及是否使用全局搜索。第四個參數傳 true 會調起系統全局搜索(例如 Google 搜索),多數情況下我們傳 false。

佈局文件

activity_main.xml 很簡單,兩個按鈕:一個觸發搜索,一個清除歷史記錄。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search" />

    <Button
        android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/clear" />
</LinearLayout>

AndroidManifest.xml

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="zhangphil.search"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="8"
              android:targetSdkVersion="22" />

    <application>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <!-- 指定默認的 searchable Activity -->
            <meta-data
                android:name="android.app.default_searchable"
                android:value=".SearchActivity" />
        </activity>

        <activity android:name=".SearchActivity">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <!-- 關聯 searchable 配置 -->
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

        <!-- 註冊 suggestions 提供者 -->
        <provider
            android:name=".ZhangPhilSuggestionProvider"
            android:authorities="ZhangPhil_AUTHORITY" />
    </application>
</manifest>

這裡有三處配置缺一不可:default_searchable 指明誰來處理搜索意圖,searchable 關聯搜索策略配置文件,<provider> 註冊建議數據的 ContentProvider。

SearchActivity:接收關鍵詞並存儲

package zhangphil.search;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.widget.Toast;

public class SearchActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            // 保存關鍵詞
            saveMyRecentQuery(intent);
        }
    }

    private void saveMyRecentQuery(Intent intent) {
        // 把搜索的關鍵詞保存到 Android 系統自帶的數據庫中
        // 如無必要定制,此過程可以使用標准、通用的方法
        String query = intent.getStringExtra(SearchManager.QUERY);

        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                ZhangPhilSuggestionProvider.AUTHORITY,
                ZhangPhilSuggestionProvider.MODE);
        suggestions.saveRecentQuery(query, null);

        Toast.makeText(this, "搜索關鍵詞:" + query, Toast.LENGTH_LONG).show();
    }
}

關鍵是判斷 Intent.ACTION_SEARCH,然後通過 SearchManager.QUERY 取出用戶輸入的關鍵詞,交給 saveRecentQuery() 落庫。saveRecentQuery() 的第二個參數是 String selectionLine,一般傳 null,只有在需要「第二行說明文字」時才使用。

SuggestionProvider:繼承系統 Provider

package zhangphil.search;

import android.content.SearchRecentSuggestionsProvider;

public class ZhangPhilSuggestionProvider extends SearchRecentSuggestionsProvider {

    // 可隨意定義一個可區別的字符串,但注意全局的唯一相同引用
    public final static String AUTHORITY = "ZhangPhil_AUTHORITY";
    public final static int MODE = DATABASE_MODE_QUERIES;

    public ZhangPhilSuggestionProvider() {
        setupSuggestions(AUTHORITY, MODE);
    }
}

整個 Provider 就這麼幾行——SearchRecentSuggestionsProvider 已經把 SQLite 建表、增刪查改、以及供搜索框查詢的 query() 方法全部實現好了,我們只需要在構造函數裡調用 setupSuggestions() 完成初始化。

MODE 的可選值有幾種:DATABASE_MODE_QUERIES 只存關鍵詞(最常用),DATABASE_MODE_QUERIES_SHORTCUTS 則支持為每條記錄配置二行文本/shortcut,適合需要展示副標題的場景。

searchable.xml

最後在 res/xml/searchable.xml 中描述搜索行為:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="https://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint"
    android:searchSuggestAuthority="ZhangPhil_AUTHORITY"
    android:searchSuggestIntentAction="android.intent.action.VIEW"
    android:searchSuggestSelection=" ?"
    android:includeInGlobalSearch="true"
    android:searchSettingsDescription="@string/search_setting" />

這裡有兩個屬性特別容易寫錯:

  • android:searchSuggestSelection:如果 Provider 使用 DATABASE_MODE_QUERIES 模式,這裡必須填空字符串;如果填 " ?" 反而是用於自定義 Provider 的場景。兩者對應關係寫反會導致點擊建議項時搜索不到結果。
  • android:includeInGlobalSearch:設為 true 表示本應用的搜索建議要參與系統全局搜索。此時必須在清單文件中為 provider 加上 android:searchSettingsDescription 描述的字符串資源,否則安裝時會報錯。

如果你的需求是「基於服務器數據的聯想」而非「基於歷史記錄的聯想」,那就不該用 SearchRecentSuggestions,而要自定義 ContentProvider 並在 query() 裡返回 SearchManager.SUGGEST_COLUMN_TEXT_1 等列——這兩種方案的區分,是實際開發中最容易混淆的一點。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved