<meta-data android:name="android.app.searchable"> 與 <provider>。ACTION_SEARCH Intent 並儲存查詢。<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="https://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/app_name"
android:searchSuggestAuthority="com.example.SearchSuggestionProvider"
android:searchSuggestSelection=" ? " />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
</activity>
<provider
android:name=".SearchSuggestionProvider"
android:authorities="com.example.SearchSuggestionProvider" />
public class SearchSuggestionProvider extends SearchRecentSuggestionsProvider {
public static final String AUTHORITY = "com.example.SearchSuggestionProvider";
public static final int MODE = DATABASE_MODE_QUERIES | DATABASE_MODE_2LINES;
public SearchSuggestionProvider() {
setupSuggestions(AUTHORITY, MODE);
}
}
public class MainActivity extends Activity {
@Override public boolean onSearchRequested() {
startSearch(null, false, null, true); // 啟動系統搜尋框
return true;
}
@Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
// 顯示結果邏輯...
// 儲存歷史
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
SearchSuggestionProvider.AUTHORITY, SearchSuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
}
}
}
// 任意位置
onSearchRequested();
// 或
startSearch(null, false, null, false);
利用系統內建 SearchRecentSuggestionsProvider 免去自建資料庫,幾行程式碼即可擁有搜尋建議與歷史記錄功能。