SearchManager.java revision 6cf7a325e6e9e70d9858e21fbb438341332ed254
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.Manifest;
20import android.content.ActivityNotFoundException;
21import android.content.ComponentName;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.DialogInterface;
25import android.content.Intent;
26import android.content.pm.ActivityInfo;
27import android.content.pm.PackageManager;
28import android.content.pm.ResolveInfo;
29import android.database.Cursor;
30import android.net.Uri;
31import android.os.Bundle;
32import android.os.Handler;
33import android.os.RemoteException;
34import android.os.ServiceManager;
35import android.text.TextUtils;
36import android.util.Log;
37import android.view.KeyEvent;
38
39import java.util.List;
40
41/**
42 * This class provides access to the system search services.
43 *
44 * <p>In practice, you won't interact with this class directly, as search
45 * services are provided through methods in {@link android.app.Activity Activity}
46 * methods and the the {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}
47 * {@link android.content.Intent Intent}.  This class does provide a basic
48 * overview of search services and how to integrate them with your activities.
49 * If you do require direct access to the SearchManager, do not instantiate
50 * this class directly; instead, retrieve it through
51 * {@link android.content.Context#getSystemService
52 * context.getSystemService(Context.SEARCH_SERVICE)}.
53 *
54 * <p>Topics covered here:
55 * <ol>
56 * <li><a href="#DeveloperGuide">Developer Guide</a>
57 * <li><a href="#HowSearchIsInvoked">How Search Is Invoked</a>
58 * <li><a href="#ImplementingSearchForYourApp">Implementing Search for Your App</a>
59 * <li><a href="#Suggestions">Search Suggestions</a>
60 * <li><a href="#ExposingSearchSuggestionsToQuickSearchBox">Exposing Search Suggestions to
61 * Quick Search Box</a></li>
62 * <li><a href="#ActionKeys">Action Keys</a>
63 * <li><a href="#SearchabilityMetadata">Searchability Metadata</a>
64 * <li><a href="#PassingSearchContext">Passing Search Context</a>
65 * <li><a href="#ProtectingUserPrivacy">Protecting User Privacy</a>
66 * </ol>
67 *
68 * <a name="DeveloperGuide"></a>
69 * <h3>Developer Guide</h3>
70 *
71 * <p>The ability to search for user, system, or network based data is considered to be
72 * a core user-level feature of the Android platform.  At any time, the user should be
73 * able to use a familiar command, button, or keystroke to invoke search, and the user
74 * should be able to search any data which is available to them.
75 *
76 * <p>To make search appear to the user as a seamless system-wide feature, the application
77 * framework centrally controls it, offering APIs to individual applications to control how they
78 * are searched. Applications can customize how search is invoked, how the search dialog looks,
79 * and what type of search results are available, including suggestions that are available as the
80 * user types.
81 *
82 * <p>Even applications which are not searchable will by default support the invocation of
83 * search to trigger Quick Search Box, the system's 'global search'.
84 *
85 * <a name="HowSearchIsInvoked"></a>
86 * <h3>How Search Is Invoked</h3>
87 *
88 * <p>Unless impossible or inapplicable, all applications should support
89 * invoking the search UI.  This means that when the user invokes the search command,
90 * a search UI will be presented to them.  The search command is currently defined as a menu
91 * item called "Search" (with an alphabetic shortcut key of "S"), or on many devices, a dedicated
92 * search button key.
93 * <p>If your application is not inherently searchable, the default implementation will cause
94 * the search UI to be invoked in a "global search" mode known as Quick Search Box.  As the user
95 * types, search suggestions from across the device and the web will be surfaced, and if they
96 * click the "Search" button, this will bring the browser to the front and will launch a web-based
97 * search.  The user will be able to click the "Back" button and return to your application.
98 * <p>In general this is implemented by your activity, or the {@link android.app.Activity Activity}
99 * base class, which captures the search command and invokes the SearchManager to
100 * display and operate the search UI.  You can also cause the search UI to be presented in response
101 * to user keystrokes in your activity (for example, to instantly start filter searching while
102 * viewing a list and typing any key).
103 * <p>The search UI is presented as a floating
104 * window and does not cause any change in the activity stack.  If the user
105 * cancels search, the previous activity re-emerges.  If the user launches a
106 * search, this will be done by sending a search {@link android.content.Intent Intent} (see below),
107 * and the normal intent-handling sequence will take place (your activity will pause,
108 * etc.)
109 * <p><b>What you need to do:</b> First, you should consider the way in which you want to
110 * handle invoking search.  There are four broad (and partially overlapping) categories for
111 * you to choose from.
112 * <ul><li>You can capture the search command yourself, by including a <i>search</i>
113 * button or menu item - and invoking the search UI directly.</li>
114 * <li>You can provide a <i>type-to-search</i> feature, in which search is invoked automatically
115 * when the user enters any characters.</li>
116 * <li>Even if your application is not inherently searchable, you can allow global search,
117 * via the search key (or even via a search menu item).
118 * <li>You can disable search entirely.  This should only be used in very rare circumstances,
119 * as search is a system-wide feature and users will expect it to be available in all contexts.</li>
120 * </ul>
121 *
122 * <p><b>How to define a search menu.</b>  The system provides the following resources which may
123 * be useful when adding a search item to your menu:
124 * <ul><li>android.R.drawable.ic_search_category_default is an icon you can use in your menu.</li>
125 * <li>{@link #MENU_KEY SearchManager.MENU_KEY} is the recommended alphabetic shortcut.</li>
126 * </ul>
127 *
128 * <p><b>How to invoke search directly.</b>  In order to invoke search directly, from a button
129 * or menu item, you can launch a generic search by calling
130 * {@link android.app.Activity#onSearchRequested onSearchRequested} as shown:
131 * <pre class="prettyprint">
132 * onSearchRequested();</pre>
133 *
134 * <p><b>How to implement type-to-search.</b>  While setting up your activity, call
135 * {@link android.app.Activity#setDefaultKeyMode setDefaultKeyMode}:
136 * <pre class="prettyprint">
137 * setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);   // search within your activity
138 * setDefaultKeyMode(DEFAULT_KEYS_SEARCH_GLOBAL);  // search using platform global search</pre>
139 *
140 * <p><b>How to start global search.</b>  In addition to searching within
141 * your activity or application, you can also use the Search Manager to invoke a platform-global
142 * search, which uses Quick Search Box to search across the device and the web.
143 * Override {@link android.app.Activity#onSearchRequested} and call
144 * {@link android.app.Activity#startSearch} with {@code globalSearch} set to {@code true}.
145 *
146 * <p><b>How to disable search from your activity.</b> Search is a system-wide feature and users
147 * will expect it to be available in all contexts.  If your UI design absolutely precludes
148 * launching search, override {@link android.app.Activity#onSearchRequested onSearchRequested}
149 * as shown:
150 * <pre class="prettyprint">
151 * &#64;Override
152 * public boolean onSearchRequested() {
153 *    return false;
154 * }</pre>
155 *
156 * <p><b>Managing focus and knowing if search is active.</b>  The search UI is not a separate
157 * activity, and when the UI is invoked or dismissed, your activity will not typically be paused,
158 * resumed, or otherwise notified by the methods defined in
159 * <a href="{@docRoot}guide/topics/fundamentals.html#actlife">Application Fundamentals:
160 * Activity Lifecycle</a>.  The search UI is
161 * handled in the same way as other system UI elements which may appear from time to time, such as
162 * notifications, screen locks, or other system alerts:
163 * <p>When the search UI appears, your activity will lose input focus.
164 * <p>When the search activity is dismissed, there are three possible outcomes:
165 * <ul><li>If the user simply canceled the search UI, your activity will regain input focus and
166 * proceed as before.  See {@link #setOnDismissListener} and {@link #setOnCancelListener} if you
167 * required direct notification of search dialog dismissals.</li>
168 * <li>If the user launched a search, and this required switching to another activity to receive
169 * and process the search {@link android.content.Intent Intent}, your activity will receive the
170 * normal sequence of activity pause or stop notifications.</li>
171 * <li>If the user launched a search, and the current activity is the recipient of the search
172 * {@link android.content.Intent Intent}, you will receive notification via the
173 * {@link android.app.Activity#onNewIntent onNewIntent()} method.</li></ul>
174 * <p>This list is provided in order to clarify the ways in which your activities will interact with
175 * the search UI.  More details on searchable activities and search intents are provided in the
176 * sections below.
177 *
178 * <a name="ImplementingSearchForYourApp"></a>
179 * <h3>Implementing Search for Your App</h3>
180 *
181 * <p>The following steps are necessary in order to implement search.
182 * <ul>
183 * <li>Implement search invocation as described above.  (Strictly speaking,
184 * these are decoupled, but it would make little sense to be "searchable" but not
185 * "search-invoking".)</li>
186 * <li>Your application should have an activity that takes a search string and
187 * converts it to a list of results.  This could be your primary display activity
188 * or it could be a dedicated search results activity.  This is your <i>searchable</i>
189 * activity and every query-search application must have one.</li>
190 * <li>In the searchable activity, in onCreate(), you must receive and handle the
191 * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}
192 * {@link android.content.Intent Intent}.  The text to search (query string) for is provided by
193 * calling
194 * {@link #QUERY getStringExtra(SearchManager.QUERY)}.</li>
195 * <li>To identify and support your searchable activity, you'll need to
196 * provide an XML file providing searchability configuration parameters, a reference to that
197 * in your searchable activity's
198 * <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> entry, and an
199 * intent-filter declaring that you can receive ACTION_SEARCH intents. This is described in more
200 * detail in the <a href="#SearchabilityMetadata">Searchability Metadata</a> section.</li>
201 * <li>Your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> also needs a
202 * metadata entry providing a global reference to the searchable activity. This is the "glue"
203 * directing the search UI, when invoked from any of your <i>other</i> activities, to use your
204 * application as the default search context.  This is also described in more detail in the
205 * <a href="#SearchabilityMetadata">Searchability Metadata</a> section.</li>
206 * <li>Finally, you may want to define your search results activity as single-top with the
207 * {@link android.R.attr#launchMode singleTop} launchMode flag.  This allows the system
208 * to launch searches from/to the same activity without creating a pile of them on the
209 * activity stack.  If you do this, be sure to also override
210 * {@link android.app.Activity#onNewIntent onNewIntent} to handle the
211 * updated intents (with new queries) as they arrive.</li>
212 * </ul>
213 *
214 * <p>Code snippet showing handling of intents in your search activity:
215 * <pre class="prettyprint">
216 * &#64;Override
217 * protected void onCreate(Bundle icicle) {
218 *     super.onCreate(icicle);
219 *
220 *     final Intent queryIntent = getIntent();
221 *     final String queryAction = queryIntent.getAction();
222 *     if (Intent.ACTION_SEARCH.equals(queryAction)) {
223 *         doSearchWithIntent(queryIntent);
224 *     }
225 * }
226 *
227 * private void doSearchWithIntent(final Intent queryIntent) {
228 *     final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
229 *     doSearchWithQuery(queryString);
230 * }</pre>
231 *
232 * <a name="Suggestions"></a>
233 * <h3>Search Suggestions</h3>
234 *
235 * <p>A powerful feature of the search system is the ability of any application to easily provide
236 * live "suggestions" in order to prompt the user.  Each application implements suggestions in a
237 * different, unique, and appropriate way.  Suggestions be drawn from many sources, including but
238 * not limited to:
239 * <ul>
240 * <li>Actual searchable results (e.g. names in the address book)</li>
241 * <li>Recently entered queries</li>
242 * <li>Recently viewed data or results</li>
243 * <li>Contextually appropriate queries or results</li>
244 * <li>Summaries of possible results</li>
245 * </ul>
246 *
247 * <p>Once an application is configured to provide search suggestions, those same suggestions can
248 * easily be made available to the system-wide Quick Search Box, providing faster access to its
249 * content from one central prominent place. See
250 * <a href="#ExposingSearchSuggestionsToQuickSearchBox">Exposing Search Suggestions to Quick Search
251 * Box</a> for more details.
252 *
253 * <p>The primary form of suggestions is known as <i>queried suggestions</i> and is based on query
254 * text that the user has already typed.  This would generally be based on partial matches in
255 * the available data.  In certain situations - for example, when no query text has been typed yet -
256 * an application may also opt to provide <i>zero-query suggestions</i>.
257 * These would typically be drawn from the same data source, but because no partial query text is
258 * available, they should be weighted based on other factors - for example, most recent queries
259 * or most recent results.
260 *
261 * <p><b>Overview of how suggestions are provided.</b>  Suggestions are accessed via a
262 * {@link android.content.ContentProvider Content Provider}. When the search manager identifies a
263 * particular activity as searchable, it will check for certain metadata which indicates that
264 * there is also a source of suggestions.  If suggestions are provided, the following steps are
265 * taken.
266 * <ul><li>Using formatting information found in the metadata, the user's query text (whatever
267 * has been typed so far) will be formatted into a query and sent to the suggestions
268 * {@link android.content.ContentProvider Content Provider}.</li>
269 * <li>The suggestions {@link android.content.ContentProvider Content Provider} will create a
270 * {@link android.database.Cursor Cursor} which can iterate over the possible suggestions.</li>
271 * <li>The search manager will populate a list using display data found in each row of the cursor,
272 * and display these suggestions to the user.</li>
273 * <li>If the user types another key, or changes the query in any way, the above steps are repeated
274 * and the suggestions list is updated or repopulated.</li>
275 * <li>If the user clicks or touches the "GO" button, the suggestions are ignored and the search is
276 * launched using the normal {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} type of
277 * {@link android.content.Intent Intent}.</li>
278 * <li>If the user uses the directional controls to navigate the focus into the suggestions list,
279 * the query text will be updated while the user navigates from suggestion to suggestion.  The user
280 * can then click or touch the updated query and edit it further.  If the user navigates back to
281 * the edit field, the original typed query is restored.</li>
282 * <li>If the user clicks or touches a particular suggestion, then a combination of data from the
283 * cursor and
284 * values found in the metadata are used to synthesize an Intent and send it to the application.
285 * Depending on the design of the activity and the way it implements search, this might be a
286 * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} (in order to launch a query), or it
287 * might be a {@link android.content.Intent#ACTION_VIEW ACTION_VIEW}, in order to proceed directly
288 * to display of specific data.</li>
289 * </ul>
290 *
291 * <p><b>Simple Recent-Query-Based Suggestions.</b>  The Android framework provides a simple Search
292 * Suggestions provider, which simply records and replays recent queries.  For many applications,
293 * this will be sufficient.  The basic steps you will need to
294 * do, in order to use the built-in recent queries suggestions provider, are as follows:
295 * <ul>
296 * <li>Implement and test query search, as described in the previous sections.</li>
297 * <li>Create a Provider within your application by extending
298 * {@link android.content.SearchRecentSuggestionsProvider}.</li>
299 * <li>Create a manifest entry describing your provider.</li>
300 * <li>Update your searchable activity's XML configuration file with information about your
301 * provider.</li>
302 * <li>In your searchable activities, capture any user-generated queries and record them
303 * for future searches by calling {@link android.provider.SearchRecentSuggestions#saveRecentQuery}.
304 * </li>
305 * </ul>
306 * <p>For complete implementation details, please refer to
307 * {@link android.content.SearchRecentSuggestionsProvider}.  The rest of the information in this
308 * section should not be necessary, as it refers to custom suggestions providers.
309 *
310 * <p><b>Creating a Customized Suggestions Provider:</b>  In order to create more sophisticated
311 * suggestion providers, you'll need to take the following steps:
312 * <ul>
313 * <li>Implement and test query search, as described in the previous sections.</li>
314 * <li>Decide how you wish to <i>receive</i> suggestions.  Just like queries that the user enters,
315 * suggestions will be delivered to your searchable activity as
316 * {@link android.content.Intent Intent} messages;  Unlike simple queries, you have quite a bit of
317 * flexibility in forming those intents.  A query search application will probably
318 * wish to continue receiving the {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}
319 * {@link android.content.Intent Intent}, which will launch a query search using query text as
320 * provided by the suggestion.  A filter search application will probably wish to
321 * receive the {@link android.content.Intent#ACTION_VIEW ACTION_VIEW}
322 * {@link android.content.Intent Intent}, which will take the user directly to a selected entry.
323 * Other interesting suggestions, including hybrids, are possible, and the suggestion provider
324 * can easily mix-and-match results to provide a richer set of suggestions for the user.  Finally,
325 * you'll need to update your searchable activity (or other activities) to receive the intents
326 * as you've defined them.</li>
327 * <li>Implement a Content Provider that provides suggestions.  If you already have one, and it
328 * has access to your suggestions data, you can use that provider. If not, you'll have to create
329 * one. You'll also provide information about your Content Provider in your
330 * package's <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a>.</li>
331 * <li>Update your searchable activity's XML configuration file.  There are two categories of
332 * information used for suggestions:
333 * <ul><li>The first is (required) data that the search manager will
334 * use to format the queries which are sent to the Content Provider.</li>
335 * <li>The second is (optional) parameters to configure structure
336 * if intents generated by suggestions.</li></li>
337 * </ul>
338 * </ul>
339 *
340 * <p><b>Configuring your Content Provider to Receive Suggestion Queries.</b>  The basic job of
341 * a search suggestions {@link android.content.ContentProvider Content Provider} is to provide
342 * "live" (while-you-type) conversion of the user's query text into a set of zero or more
343 * suggestions. Each application is free to define the conversion, and as described above there are
344 * many possible solutions.  This section simply defines how to communicate with the suggestion
345 * provider.
346 *
347 * <p>The Search Manager must first determine if your package provides suggestions.  This is done
348 * by examination of your searchable meta-data XML file.  The android:searchSuggestAuthority
349 * attribute, if provided, is the signal to obtain & display suggestions.
350 *
351 * <p>Every query includes a Uri, and the Search Manager will format the Uri as shown:
352 * <p><pre class="prettyprint">
353 * content:// your.suggest.authority / your.suggest.path / SearchManager.SUGGEST_URI_PATH_QUERY
354 *    </pre>
355 *
356 * <p>Your Content Provider can receive the query text in one of two ways.
357 * <ul>
358 * <li><b>Query provided as a selection argument.</b>  If you define the attribute value
359 * android:searchSuggestSelection and include a string, this string will be passed as the
360 * <i>selection</i> parameter to your Content Provider's query function.  You must define a single
361 * selection argument, using the '?' character.  The user's query text will be passed to you
362 * as the first element of the selection arguments array.</li>
363 * <li><b>Query provided with Data Uri.</b>  If you <i>do not</i> define the attribute value
364 * android:searchSuggestSelection, then the Search Manager will append another "/" followed by
365 * the user's query to the query Uri.  The query will be encoding using Uri encoding rules - don't
366 * forget to decode it.  (See {@link android.net.Uri#getPathSegments} and
367 * {@link android.net.Uri#getLastPathSegment} for helpful utilities you can use here.)</li>
368 * </ul>
369 *
370 * <p><b>Providing access to Content Providers that require permissions.</b>  If your content
371 * provider declares an android:readPermission in your application's manifest, you must provide
372 * access to the search infrastructure to the search suggestion path by including a path-permission
373 * that grants android:readPermission access to "android.permission.GLOBAL_SEARCH". Granting access
374 * explicitly to the search infrastructure ensures it will be able to access the search suggestions
375 * without needing to know ahead of time any other details of the permissions protecting your
376 * provider.  Content providers that require no permissions are already available to the search
377 * infrastructure.  Here is an example of a provider that protects access to it with permissions,
378 * and provides read access to the search infrastructure to the path that it expects to receive the
379 * suggestion query on:
380 * <pre class="prettyprint">
381 * &lt;provider android:name="MyProvider" android:authorities="myprovider"
382 *        android:readPermission="android.permission.READ_MY_DATA"
383 *        android:writePermission="android.permission.WRITE_MY_DATA"&gt;
384 *    &lt;path-permission android:path="/search_suggest_query"
385 *            android:readPermission="android.permission.GLOBAL_SEARCH" /&gt;
386 * &lt;/provider&gt;
387 * </pre>
388 *
389 * <p><b>Handling empty queries.</b>  Your application should handle the "empty query"
390 * (no user text entered) case properly, and generate useful suggestions in this case.  There are a
391 * number of ways to do this;  Two are outlined here:
392 * <ul><li>For a simple filter search of local data, you could simply present the entire dataset,
393 * unfiltered.  (example: People)</li>
394 * <li>For a query search, you could simply present the most recent queries.  This allows the user
395 * to quickly repeat a recent search.</li></ul>
396 *
397 * <p><b>The Format of Individual Suggestions.</b>  Your suggestions are communicated back to the
398 * Search Manager by way of a {@link android.database.Cursor Cursor}.  The Search Manager will
399 * usually pass a null Projection, which means that your provider can simply return all appropriate
400 * columns for each suggestion.  The columns currently defined are:
401 *
402 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
403 *
404 *     <thead>
405 *     <tr><th>Column Name</th> <th>Description</th> <th>Required?</th></tr>
406 *     </thead>
407 *
408 *     <tbody>
409 *     <tr><th>{@link #SUGGEST_COLUMN_FORMAT}</th>
410 *         <td><i>Unused - can be null.</i></td>
411 *         <td align="center">No</td>
412 *     </tr>
413 *
414 *     <tr><th>{@link #SUGGEST_COLUMN_TEXT_1}</th>
415 *         <td>This is the line of text that will be presented to the user as the suggestion.</td>
416 *         <td align="center">Yes</td>
417 *     </tr>
418 *
419 *     <tr><th>{@link #SUGGEST_COLUMN_TEXT_2}</th>
420 *         <td>If your cursor includes this column, then all suggestions will be provided in a
421 *             two-line format.  The data in this column will be displayed as a second, smaller
422 *             line of text below the primary suggestion, or it can be null or empty to indicate no
423 *             text in this row's suggestion.</td>
424 *         <td align="center">No</td>
425 *     </tr>
426 *
427 *     <tr><th>{@link #SUGGEST_COLUMN_ICON_1}</th>
428 *         <td>If your cursor includes this column, then all suggestions will be provided in an
429 *             icons+text format.  This value should be a reference to the icon to
430 *             draw on the left side, or it can be null or zero to indicate no icon in this row.
431 *             </td>
432 *         <td align="center">No.</td>
433 *     </tr>
434 *
435 *     <tr><th>{@link #SUGGEST_COLUMN_ICON_2}</th>
436 *         <td>If your cursor includes this column, then all suggestions will be provided in an
437 *             icons+text format.  This value should be a reference to the icon to
438 *             draw on the right side, or it can be null or zero to indicate no icon in this row.
439 *             </td>
440 *         <td align="center">No.</td>
441 *     </tr>
442 *
443 *     <tr><th>{@link #SUGGEST_COLUMN_INTENT_ACTION}</th>
444 *         <td>If this column exists <i>and</i> this element exists at the given row, this is the
445 *             action that will be used when forming the suggestion's intent.  If the element is
446 *             not provided, the action will be taken from the android:searchSuggestIntentAction
447 *             field in your XML metadata.  <i>At least one of these must be present for the
448 *             suggestion to generate an intent.</i>  Note:  If your action is the same for all
449 *             suggestions, it is more efficient to specify it using XML metadata and omit it from
450 *             the cursor.</td>
451 *         <td align="center">No</td>
452 *     </tr>
453 *
454 *     <tr><th>{@link #SUGGEST_COLUMN_INTENT_DATA}</th>
455 *         <td>If this column exists <i>and</i> this element exists at the given row, this is the
456 *             data that will be used when forming the suggestion's intent.  If the element is not
457 *             provided, the data will be taken from the android:searchSuggestIntentData field in
458 *             your XML metadata.  If neither source is provided, the Intent's data field will be
459 *             null.  Note:  If your data is the same for all suggestions, or can be described
460 *             using a constant part and a specific ID, it is more efficient to specify it using
461 *             XML metadata and omit it from the cursor.</td>
462 *         <td align="center">No</td>
463 *     </tr>
464 *
465 *     <tr><th>{@link #SUGGEST_COLUMN_INTENT_DATA_ID}</th>
466 *         <td>If this column exists <i>and</i> this element exists at the given row, then "/" and
467 *             this value will be appended to the data field in the Intent.  This should only be
468 *             used if the data field has already been set to an appropriate base string.</td>
469 *         <td align="center">No</td>
470 *     </tr>
471 *
472 *     <tr><th>{@link #SUGGEST_COLUMN_INTENT_EXTRA_DATA}</th>
473 *         <td>If this column exists <i>and</i> this element exists at a given row, this is the
474 *             data that will be used when forming the suggestion's intent.  If not provided,
475 *             the Intent's extra data field will be null.  This column allows suggestions to
476 *             provide additional arbitrary data which will be included as an extra under the
477 *             key {@link #EXTRA_DATA_KEY}.</td>
478 *         <td align="center">No.</td>
479 *     </tr>
480 *
481 *     <tr><th>{@link #SUGGEST_COLUMN_QUERY}</th>
482 *         <td>If this column exists <i>and</i> this element exists at the given row, this is the
483 *             data that will be used when forming the suggestion's query.</td>
484 *         <td align="center">Required if suggestion's action is
485 *             {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}, optional otherwise.</td>
486 *     </tr>
487 *
488 *     <tr><th>{@link #SUGGEST_COLUMN_SHORTCUT_ID}</th>
489 *         <td>This column is used to indicate whether a search suggestion should be stored as a
490 *             shortcut, and whether it should be validated.  Shortcuts are usually formed when the
491 *             user clicks a suggestion from Quick Search Box.  If missing, the result will be
492 *             stored as a shortcut and never refreshed.  If set to
493 *             {@link #SUGGEST_NEVER_MAKE_SHORTCUT}, the result will not be stored as a shortcut.
494 *             Otherwise, the shortcut id will be used to check back for for an up to date
495 *             suggestion using {@link #SUGGEST_URI_PATH_SHORTCUT}. Read more about shortcut
496 *             refreshing in the section about
497 *             <a href="#ExposingSearchSuggestionsToQuickSearchBox">exposing search suggestions to
498 *             Quick Search Box</a>.</td>
499 *         <td align="center">No.  Only applicable to sources included in Quick Search Box.</td>
500 *     </tr>
501 *
502 *     <tr><th>{@link #SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING}</th>
503 *         <td>This column is used to specify that a spinner should be shown in lieu of an icon2
504 *             while the shortcut of this suggestion is being refreshed in Quick Search Box.</td>
505 *         <td align="center">No.  Only applicable to sources included in Quick Search Box.</td>
506 *     </tr>
507 *
508 *     <tr><th><i>Other Columns</i></th>
509 *         <td>Finally, if you have defined any <a href="#ActionKeys">Action Keys</a> and you wish
510 *             for them to have suggestion-specific definitions, you'll need to define one
511 *             additional column per action key.  The action key will only trigger if the
512 *             currently-selection suggestion has a non-empty string in the corresponding column.
513 *             See the section on <a href="#ActionKeys">Action Keys</a> for additional details and
514 *             implementation steps.</td>
515 *         <td align="center">No</td>
516 *     </tr>
517 *
518 *     </tbody>
519 * </table>
520 *
521 * <p>Clearly there are quite a few permutations of your suggestion data, but in the next section
522 * we'll look at a few simple combinations that you'll select from.
523 *
524 * <p><b>The Format Of Intents Sent By Search Suggestions.</b>  Although there are many ways to
525 * configure these intents, this document will provide specific information on just a few of them.
526 * <ul><li><b>Launch a query.</b>  In this model, each suggestion represents a query that your
527 * searchable activity can perform, and the {@link android.content.Intent Intent} will be formatted
528 * exactly like those sent when the user enters query text and clicks the "GO" button:
529 *   <ul>
530 *   <li><b>Action:</b> {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} provided
531 *   using your XML metadata (android:searchSuggestIntentAction).</li>
532 *   <li><b>Data:</b> empty (not used).</li>
533 *   <li><b>Query:</b> query text supplied by the cursor.</li>
534 *   </ul>
535 * </li>
536 * <li><b>Go directly to a result, using a complete Data Uri.</b>  In this model, the user will be
537 * taken directly to a specific result.
538 *   <ul>
539 *   <li><b>Action:</b> {@link android.content.Intent#ACTION_VIEW ACTION_VIEW}</li>
540 *   <li><b>Data:</b> a complete Uri, supplied by the cursor, that identifies the desired data.
541 *   </li>
542 *   <li><b>Query:</b> query text supplied with the suggestion (probably ignored)</li>
543 *   </ul>
544 * </li>
545 * <li><b>Go directly to a result, using a synthesized Data Uri.</b>  This has the same result
546 * as the previous suggestion, but provides the Data Uri in a different way.
547 *   <ul>
548 *   <li><b>Action:</b> {@link android.content.Intent#ACTION_VIEW ACTION_VIEW}</li>
549 *   <li><b>Data:</b> The search manager will assemble a Data Uri using the following elements:
550 *   a Uri fragment provided in your XML metadata (android:searchSuggestIntentData), followed by
551 *   a single "/", followed by the value found in the {@link #SUGGEST_COLUMN_INTENT_DATA_ID}
552 *   entry in your cursor.</li>
553 *   <li><b>Query:</b> query text supplied with the suggestion (probably ignored)</li>
554 *   </ul>
555 * </li>
556 * </ul>
557 * <p>This list is not meant to be exhaustive.  Applications should feel free to define other types
558 * of suggestions.  For example, you could reduce long lists of results to summaries, and use one
559 * of the above intents (or one of your own) with specially formatted Data Uri's to display more
560 * detailed results.  Or you could display textual shortcuts as suggestions, but launch a display
561 * in a more data-appropriate format such as media artwork.
562 *
563 * <p><b>Suggestion Rewriting.</b>  If the user navigates through the suggestions list, the UI
564 * may temporarily rewrite the user's query with a query that matches the currently selected
565 * suggestion. This enables the user to see what query is being suggested, and also allows the user
566 * to click or touch in the entry EditText element and make further edits to the query before
567 * dispatching it.  In order to perform this correctly, the Search UI needs to know exactly what
568 * text to rewrite the query with.
569 *
570 * <p>For each suggestion, the following logic is used to select a new query string:
571 * <ul><li>If the suggestion provides an explicit value in the {@link #SUGGEST_COLUMN_QUERY}
572 * column, this value will be used.</li>
573 * <li>If the metadata includes the queryRewriteFromData flag, and the suggestion provides an
574 * explicit value for the intent Data field, this Uri will be used.  Note that this should only be
575 * used with Uri's that are intended to be user-visible, such as HTTP.  Internal Uri schemes should
576 * not be used in this way.</li>
577 * <li>If the metadata includes the queryRewriteFromText flag, the text in
578 * {@link #SUGGEST_COLUMN_TEXT_1} will be used.  This should be used for suggestions in which no
579 * query text is provided and the SUGGEST_COLUMN_INTENT_DATA values are not suitable for user
580 * inspection and editing.</li></ul>
581 *
582 * <a name="ExposingSearchSuggestionsToQuickSearchBox"></a>
583 * <h3>Exposing Search Suggestions to Quick Search Box</h3>
584 *
585 * <p>Once your application is set up to provide search suggestions, making them available to the
586 * globally accessable Quick Search Box is as easy as setting android:includeInGlobalSearch to
587 * "true" in your searchable metadata file.  Beyond that, here are some more details of how
588 * suggestions interact with Quick Search Box, and optional ways that you may customize suggestions
589 * for your application.
590 *
591 * <p><b>Important Note:</b>  By default, your application will not be enabled as a suggestion
592 * provider (or "searchable item") in Quick Search Box. Once your app is installed, the user must
593 * enable it as a "searchable item" in the Search settings in order to receive your app's
594 * suggestions in Quick Search Box. You should consider how to message this to users of your app -
595 * perhaps with a note to the user the first time they launch the app about how to enable search
596 * suggestions. This gives your app a chance to be queried for suggestions as the user types into
597 * Quick Search Box, though exactly how or if your suggestions will be surfaced is decided by Quick
598 * Search Box.
599 *
600 * <p><b>Source Ranking:</b>  Once your application's search results are made available to Quick
601 * Search Box, how they surface to the user for a particular query will be determined as appropriate
602 * by Quick Search Box ranking. This may depend on how many other apps have results for that query,
603 * and how often the user has clicked on your results compared to the other apps - but there is no
604 * guarantee about how ranking will occur, or whether your app's suggestions will show at all for
605 * a given query.  In general, you can expect that providing quality results will increase the
606 * likelihood that your app's suggestions are provided in a prominent position, and apps that
607 * provide lower quality suggestions will be more likely to be ranked lower and/or not displayed.
608 *
609 * <p><b>Search Settings:</b>  Each app that is available to Quick Search Box has an entry in the
610 * system settings where the user can enable or disable the inclusion of its results.  Below the
611 * name of the application, each application may provide a brief description of what kind of
612 * information will be made available via a search settings description string pointed to by the
613 * android:searchSettingsDescription attribute in the searchable metadata. Note that the
614 * user will need to visit this settings menu to enable search suggestions for your app before your
615 * app will have a chance to provide search suggestions to Quick Search Box - see the section
616 * called "Important Note" above.
617 *
618 * <p><b>Shortcuts:</b>  Suggestions that are clicked on by the user may be automatically made into
619 * shortcuts, which are suggestions that have been copied from your provider in order to be quickly
620 * displayed without the need to re-query the original sources. Shortcutted suggestions may be
621 * displayed for the query that yielded the suggestion and for any prefixes of that query. You can
622 * request how to have your app's suggestions made into shortcuts, and whether they should be
623 * refreshed, using the {@link #SUGGEST_COLUMN_SHORTCUT_ID} column:
624 * <ul><li>Suggestions that do not include a shortcut id column will be made into shortcuts and
625 * never refreshed.  This makes sense for suggestions that refer to data that will never be changed
626 * or removed.</li>
627 * <li>Suggestions that include a shortcut id will be re-queried for a fresh version of the
628 * suggestion each time the shortcut is displayed.  The shortcut will be quickly displayed with
629 * whatever data was most recently available until the refresh query returns, after which the
630 * suggestion will be dynamically refreshed with the up to date information.  The shortcut refresh
631 * query will be sent to your suggestion provider with a uri of {@link #SUGGEST_URI_PATH_SHORTCUT}.
632 * The result should contain one suggestion using the same columns as the suggestion query, or be
633 * empty, indicating that the shortcut is no longer valid.  Shortcut ids make sense when referring
634 * to data that may change over time, such as a contact's presence status.  If a suggestion refers
635 * to data that could take longer to refresh, such as a network based refresh of a stock quote, you
636 * may include {@link #SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING} to show a progress spinner for the
637 * right hand icon until the refresh is complete.</li>
638 * <li>Finally, to prevent a suggestion from being copied into a shortcut, you may provide a
639 * shortcut id with a value of {@link #SUGGEST_NEVER_MAKE_SHORTCUT}.</li></ul>
640 *
641 * Note that Quick Search Box will ultimately decide whether to shortcut your app's suggestions,
642 * considering these values as a strong request from your application.
643 *
644 * <a name="ActionKeys"></a>
645 * <h3>Action Keys</h3>
646 *
647 * <p>Searchable activities may also wish to provide shortcuts based on the various action keys
648 * available on the device.  The most basic example of this is the contacts app, which enables the
649 * green "dial" key for quick access during searching.  Not all action keys are available on
650 * every device, and not all are allowed to be overriden in this way.  (For example, the "Home"
651 * key must always return to the home screen, with no exceptions.)
652 *
653 * <p>In order to define action keys for your searchable application, you must do two things.
654 *
655 * <ul>
656 * <li>You'll add one or more <i>actionkey</i> elements to your searchable metadata configuration
657 * file.  Each element defines one of the keycodes you are interested in,
658 * defines the conditions under which they are sent, and provides details
659 * on how to communicate the action key event back to your searchable activity.</li>
660 * <li>In your broadcast receiver, if you wish, you can check for action keys by checking the
661 * extras field of the {@link android.content.Intent Intent}.</li>
662 * </ul>
663 *
664 * <p><b>Updating metadata.</b>  For each keycode of interest, you must add an &lt;actionkey&gt;
665 * element.  Within this element you must define two or three attributes.  The first attribute,
666 * &lt;android:keycode&gt;, is required;  It is the key code of the action key event, as defined in
667 * {@link android.view.KeyEvent}.  The remaining two attributes define the value of the actionkey's
668 * <i>message</i>, which will be passed to your searchable activity in the
669 * {@link android.content.Intent Intent} (see below for more details).  Although each of these
670 * attributes is optional, you must define one or both for the action key to have any effect.
671 * &lt;android:queryActionMsg&gt; provides the message that will be sent if the action key is
672 * pressed while the user is simply entering query text.  &lt;android:suggestActionMsgColumn&gt;
673 * is used when action keys are tied to specific suggestions.  This attribute provides the name
674 * of a <i>column</i> in your suggestion cursor;  The individual suggestion, in that column,
675 * provides the message.  (If the cell is empty or null, that suggestion will not work with that
676 * action key.)
677 * <p>See the <a href="#SearchabilityMetadata">Searchability Metadata</a> section for more details
678 * and examples.
679 *
680 * <p><b>Receiving Action Keys</b>  Intents launched by action keys will be specially marked
681 * using a combination of values.  This enables your searchable application to examine the intent,
682 * if necessary, and perform special processing.  For example, clicking a suggested contact might
683 * simply display them;  Selecting a suggested contact and clicking the dial button might
684 * immediately call them.
685 *
686 * <p>When a search {@link android.content.Intent Intent} is launched by an action key, two values
687 * will be added to the extras field.
688 * <ul>
689 * <li>To examine the key code, use {@link android.content.Intent#getIntExtra
690 * getIntExtra(SearchManager.ACTION_KEY)}.</li>
691 * <li>To examine the message string, use {@link android.content.Intent#getStringExtra
692 * getStringExtra(SearchManager.ACTION_MSG)}</li>
693 * </ul>
694 *
695 * <a name="SearchabilityMetadata"></a>
696 * <h3>Searchability Metadata</h3>
697 *
698 * <p>Every activity that is searchable must provide a small amount of additional information
699 * in order to properly configure the search system.  This controls the way that your search
700 * is presented to the user, and controls for the various modalities described previously.
701 *
702 * <p>If your application is not searchable,
703 * then you do not need to provide any search metadata, and you can skip the rest of this section.
704 * When this search metadata cannot be found, the search manager will assume that the activity
705 * does not implement search.  (Note: to implement web-based search, you will need to add
706 * the android.app.default_searchable metadata to your manifest, as shown below.)
707 *
708 * <p>Values you supply in metadata apply only to each local searchable activity.  Each
709 * searchable activity can define a completely unique search experience relevant to its own
710 * capabilities and user experience requirements, and a single application can even define multiple
711 * searchable activities.
712 *
713 * <p><b>Metadata for searchable activity.</b>  As with your search implementations described
714 * above, you must first identify which of your activities is searchable.  In the
715 * <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> entry for this activity, you must
716 * provide two elements:
717 * <ul><li>An intent-filter specifying that you can receive and process the
718 * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} {@link android.content.Intent Intent}.
719 * </li>
720 * <li>A reference to a small XML file (typically called "searchable.xml") which contains the
721 * remaining configuration information for how your application implements search.</li></ul>
722 *
723 * <p>Here is a snippet showing the necessary elements in the
724 * <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> entry for your searchable activity.
725 * <pre class="prettyprint">
726 *        &lt;!-- Search Activity - searchable --&gt;
727 *        &lt;activity android:name="MySearchActivity"
728 *                  android:label="Search"
729 *                  android:launchMode="singleTop"&gt;
730 *            &lt;intent-filter&gt;
731 *                &lt;action android:name="android.intent.action.SEARCH" /&gt;
732 *                &lt;category android:name="android.intent.category.DEFAULT" /&gt;
733 *            &lt;/intent-filter&gt;
734 *            &lt;meta-data android:name="android.app.searchable"
735 *                       android:resource="@xml/searchable" /&gt;
736 *        &lt;/activity&gt;</pre>
737 *
738 * <p>Next, you must provide the rest of the searchability configuration in
739 * the small XML file, stored in the ../xml/ folder in your build.  The XML file is a
740 * simple enumeration of the search configuration parameters for searching within this activity,
741 * application, or package.  Here is a sample XML file (named searchable.xml, for use with
742 * the above manifest) for a query-search activity.
743 *
744 * <pre class="prettyprint">
745 * &lt;searchable xmlns:android="http://schemas.android.com/apk/res/android"
746 *     android:label="@string/search_label"
747 *     android:hint="@string/search_hint" &gt;
748 * &lt;/searchable&gt;</pre>
749 *
750 * <p>Note that all user-visible strings <i>must</i> be provided in the form of "@string"
751 * references.  Hard-coded strings, which cannot be localized, will not work properly in search
752 * metadata.
753 *
754 * <p>Attributes you can set in search metadata:
755 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
756 *
757 *     <thead>
758 *     <tr><th>Attribute</th> <th>Description</th> <th>Required?</th></tr>
759 *     </thead>
760 *
761 *     <tbody>
762 *     <tr><th>android:label</th>
763 *         <td>This is the name for your application that will be presented to the user in a
764 *             list of search targets, or in the search box as a label.</td>
765 *         <td align="center">Yes</td>
766 *     </tr>
767 *
768 *     <tr><th>android:icon</th>
769 *         <td><strong>This is deprecated.</strong><br/>The default
770 *           application icon is now always used, so this attribute is
771 *           obsolete.</td>
772 *         <td align="center">No</td>
773 *     </tr>
774 *
775 *     <tr><th>android:hint</th>
776 *         <td>This is the text to display in the search text field when no text
777 *             has been entered by the user.</td>
778 *         <td align="center">No</td>
779 *     </tr>
780 *
781 *     <tr><th>android:searchMode</th>
782 *         <td>If provided and non-zero, sets additional modes for control of the search
783 *             presentation.  The following mode bits are defined:
784 *             <table border="2" align="center" frame="hsides" rules="rows">
785 *                 <tbody>
786 *                 <tr><th>showSearchLabelAsBadge</th>
787 *                     <td>If set, this flag enables the display of the search target (label)
788 *                         above the search box. As an alternative, you may
789 *                         want to instead use "hint" text in the search box.
790 *                         See the "android:hint" attribute above.</td>
791 *                 </tr>
792 *                 <tr><th>showSearchIconAsBadge</th>
793 *                     <td><strong>This is deprecated.</strong><br/>The default
794 *                         application icon is now always used, so this
795 *                         option is obsolete.</td>
796 *                 </tr>
797 *                 <tr><th>queryRewriteFromData</th>
798 *                     <td>If set, this flag causes the suggestion column SUGGEST_COLUMN_INTENT_DATA
799 *                         to be considered as the text for suggestion query rewriting.  This should
800 *                         only be used when the values in SUGGEST_COLUMN_INTENT_DATA are suitable
801 *                         for user inspection and editing - typically, HTTP/HTTPS Uri's.</td>
802 *                 </tr>
803 *                 <tr><th>queryRewriteFromText</th>
804 *                     <td>If set, this flag causes the suggestion column SUGGEST_COLUMN_TEXT_1 to
805 *                         be considered as the text for suggestion query rewriting.  This should
806 *                         be used for suggestions in which no query text is provided and the
807 *                         SUGGEST_COLUMN_INTENT_DATA values are not suitable for user inspection
808 *                         and editing.</td>
809 *                 </tr>
810 *                 </tbody>
811 *            </table>
812 *            Note that the icon of your app will likely be shown alongside any badge you specify,
813 *            to differentiate search in your app from Quick Search Box. The display of this icon
814 *            is not under the app's control.
815 *         </td>
816 *
817 *         <td align="center">No</td>
818 *     </tr>
819 *
820 *     <tr><th>android:inputType</th>
821 *         <td>If provided, supplies a hint about the type of search text the user will be
822 *             entering.  For most searches, in which free form text is expected, this attribute
823 *             need not be provided.  Suitable values for this attribute are described in the
824 *             <a href="../R.attr.html#inputType">inputType</a> attribute.</td>
825 *         <td align="center">No</td>
826 *     </tr>
827 *     <tr><th>android:imeOptions</th>
828 *         <td>If provided, supplies additional options for the input method.
829 *             For most searches, in which free form text is expected, this attribute
830 *             need not be provided, and will default to "actionSearch".
831 *             Suitable values for this attribute are described in the
832 *             <a href="../R.attr.html#imeOptions">imeOptions</a> attribute.</td>
833 *         <td align="center">No</td>
834 *     </tr>
835 *
836 *     </tbody>
837 * </table>
838 *
839 * <p><b>Styleable Resources in your Metadata.</b>  It's possible to provide alternate strings
840 * for your searchable application, in order to provide localization and/or to better visual
841 * presentation on different device configurations.  Each searchable activity has a single XML
842 * metadata file, but any resource references can be replaced at runtime based on device
843 * configuration, language setting, and other system inputs.
844 *
845 * <p>A concrete example is the "hint" text you supply using the android:searchHint attribute.
846 * In portrait mode you'll have less screen space and may need to provide a shorter string, but
847 * in landscape mode you can provide a longer, more descriptive hint.  To do this, you'll need to
848 * define two or more strings.xml files, in the following directories:
849 * <ul><li>.../res/values-land/strings.xml</li>
850 * <li>.../res/values-port/strings.xml</li>
851 * <li>.../res/values/strings.xml</li></ul>
852 *
853 * <p>For more complete documentation on this capability, see
854 * <a href="{@docRoot}guide/topics/resources/resources-i18n.html#AlternateResources">Resources and
855 * Internationalization: Alternate Resources</a>.
856 *
857 * <p><b>Metadata for non-searchable activities.</b>  Activities which are part of a searchable
858 * application, but don't implement search itself, require a bit of "glue" in order to cause
859 * them to invoke search using your searchable activity as their primary context.  If this is not
860 * provided, then searches from these activities will use the system default search context.
861 *
862 * <p>The simplest way to specify this is to add a <i>search reference</i> element to the
863 * application entry in the <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> file.
864 * The value of this reference should be the name of your searchable activity.
865 * It is typically prefixed by '.' to indicate that it's in the same package.
866 *
867 * <p>Here is a snippet showing the necessary addition to the manifest entry for your
868 * non-searchable activities.
869 * <pre class="prettyprint">
870 *        &lt;application&gt;
871 *            &lt;meta-data android:name="android.app.default_searchable"
872 *                       android:value=".MySearchActivity" /&gt;
873 *
874 *            &lt;!-- followed by activities, providers, etc... --&gt;
875 *        &lt;/application&gt;</pre>
876 *
877 * <p>You can also specify android.app.default_searchable on a per-activity basis, by including
878 * the meta-data element (as shown above) in one or more activity sections.  If found, these will
879 * override the reference in the application section.  The only reason to configure your application
880 * this way would be if you wish to partition it into separate sections with different search
881 * behaviors;  Otherwise this configuration is not recommended.
882 *
883 * <p><b>Additional metadata for search suggestions.</b>  If you have defined a content provider
884 * to generate search suggestions, you'll need to publish it to the system, and you'll need to
885 * provide a bit of additional XML metadata in order to configure communications with it.
886 *
887 * <p>First, in your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a>, you'll add the
888 * following lines.
889 * <pre class="prettyprint">
890 *        &lt;!-- Content provider for search suggestions --&gt;
891 *        &lt;provider android:name="YourSuggestionProviderClass"
892 *                android:authorities="your.suggestion.authority" /&gt;</pre>
893 *
894 * <p>Next, you'll add a few lines to your XML metadata file, as shown:
895 * <pre class="prettyprint">
896 *     &lt;!-- Required attribute for any suggestions provider --&gt;
897 *     android:searchSuggestAuthority="your.suggestion.authority"
898 *
899 *     &lt;!-- Optional attribute for configuring queries --&gt;
900 *     android:searchSuggestSelection="field =?"
901 *
902 *     &lt;!-- Optional attributes for configuring intent construction --&gt;
903 *     android:searchSuggestIntentAction="intent action string"
904 *     android:searchSuggestIntentData="intent data Uri" /&gt;</pre>
905 *
906 * <p>Elements of search metadata that support suggestions:
907 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
908 *
909 *     <thead>
910 *     <tr><th>Attribute</th> <th>Description</th> <th>Required?</th></tr>
911 *     </thead>
912 *
913 *     <tbody>
914 *     <tr><th>android:searchSuggestAuthority</th>
915 *         <td>This value must match the authority string provided in the <i>provider</i> section
916 *             of your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a>.</td>
917 *         <td align="center">Yes</td>
918 *     </tr>
919 *
920 *     <tr><th>android:searchSuggestPath</th>
921 *         <td>If provided, this will be inserted in the suggestions query Uri, after the authority
922 *             you have provide but before the standard suggestions path.  This is only required if
923 *             you have a single content provider issuing different types of suggestions (e.g. for
924 *             different data types) and you need a way to disambiguate the suggestions queries
925 *             when they are received.</td>
926 *         <td align="center">No</td>
927 *     </tr>
928 *
929 *     <tr><th>android:searchSuggestSelection</th>
930 *         <td>If provided, this value will be passed into your query function as the
931 *             <i>selection</i> parameter.  Typically this will be a WHERE clause for your database,
932 *             and will contain a single question mark, which represents the actual query string
933 *             that has been typed by the user.  However, you can also use any non-null value
934 *             to simply trigger the delivery of the query text (via selection arguments), and then
935 *             use the query text in any way appropriate for your provider (ignoring the actual
936 *             text of the selection parameter.)</td>
937 *         <td align="center">No</td>
938 *     </tr>
939 *
940 *     <tr><th>android:searchSuggestIntentAction</th>
941 *         <td>If provided, and not overridden by the selected suggestion, this value will be
942 *             placed in the action field of the {@link android.content.Intent Intent} when the
943 *             user clicks a suggestion.</td>
944 *         <td align="center">No</td>
945 *
946 *     <tr><th>android:searchSuggestIntentData</th>
947 *         <td>If provided, and not overridden by the selected suggestion, this value will be
948 *             placed in the data field of the {@link android.content.Intent Intent} when the user
949 *             clicks a suggestion.</td>
950 *         <td align="center">No</td>
951 *     </tr>
952 *
953 *     </tbody>
954 * </table>
955 *
956 * <p>Elements of search metadata that configure search suggestions being available to Quick Search
957 * Box:
958 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
959 *
960 *     <thead>
961 *     <tr><th>Attribute</th> <th>Description</th> <th>Required?</th></tr>
962 *     </thead>
963 *
964 *     <tr><th>android:includeInGlobalSearch</th>
965 *         <td>If true, indicates the search suggestions provided by your application should be
966 *             included in the globally accessible Quick Search Box.  The attributes below are only
967 *             applicable if this is set to true.</td>
968 *         <td align="center">Yes</td>
969 *     </tr>
970 *
971 *     <tr><th>android:searchSettingsDescription</th>
972 *         <td>If provided, provides a brief description of the search suggestions that are provided
973 *             by your application to Quick Search Box, and will be displayed in the search settings
974 *             entry for your application.</td>
975 *         <td align="center">No</td>
976 *     </tr>
977 *
978 *     <tr><th>android:queryAfterZeroResults</th>
979 *         <td>Indicates whether a source should be invoked for supersets of queries it has
980 *             returned zero results for in the past.  For example, if a source returned zero
981 *             results for "bo", it would be ignored for "bob".  If set to false, this source
982 *             will only be ignored for a single session; the next time the search dialog is
983 *             invoked, all sources will be queried.  The default value is false.</td>
984 *         <td align="center">No</td>
985 *     </tr>
986 *
987 *     <tr><th>android:searchSuggestThreshold</th>
988 *         <td>Indicates the minimum number of characters needed to trigger a source from Quick
989 *             Search Box.  Only guarantees that a source will not be queried for anything shorter
990 *             than the threshold.  The default value is 0.</td>
991 *         <td align="center">No</td>
992 *     </tr>
993 *
994 *     </tbody>
995 * </table>
996 *
997 * <p><b>Additional metadata for search action keys.</b>  For each action key that you would like to
998 * define, you'll need to add an additional element defining that key, and using the attributes
999 * discussed in <a href="#ActionKeys">Action Keys</a>.  A simple example is shown here:
1000 *
1001 * <pre class="prettyprint">&lt;actionkey
1002 *     android:keycode="KEYCODE_CALL"
1003 *     android:queryActionMsg="call"
1004 *     android:suggestActionMsg="call"
1005 *     android:suggestActionMsgColumn="call_column" /&gt;</pre>
1006 *
1007 * <p>Elements of search metadata that support search action keys.  Note that although each of the
1008 * action message elements are marked as <i>optional</i>, at least one must be present for the
1009 * action key to have any effect.
1010 *
1011 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
1012 *
1013 *     <thead>
1014 *     <tr><th>Attribute</th> <th>Description</th> <th>Required?</th></tr>
1015 *     </thead>
1016 *
1017 *     <tbody>
1018 *     <tr><th>android:keycode</th>
1019 *         <td>This attribute denotes the action key you wish to respond to.  Note that not
1020 *             all action keys are actually supported using this mechanism, as many of them are
1021 *             used for typing, navigation, or system functions.  This will be added to the
1022 *             {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} intent that is passed to
1023 *             your searchable activity.  To examine the key code, use
1024 *             {@link android.content.Intent#getIntExtra getIntExtra(SearchManager.ACTION_KEY)}.
1025 *             <p>Note, in addition to the keycode, you must also provide one or more of the action
1026 *             specifier attributes.</td>
1027 *         <td align="center">Yes</td>
1028 *     </tr>
1029 *
1030 *     <tr><th>android:queryActionMsg</th>
1031 *         <td>If you wish to handle an action key during normal search query entry, you
1032 *          must define an action string here.  This will be added to the
1033 *          {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} intent that is passed to your
1034 *          searchable activity.  To examine the string, use
1035 *          {@link android.content.Intent#getStringExtra
1036 *          getStringExtra(SearchManager.ACTION_MSG)}.</td>
1037 *         <td align="center">No</td>
1038 *     </tr>
1039 *
1040 *     <tr><th>android:suggestActionMsg</th>
1041 *         <td>If you wish to handle an action key while a suggestion is being displayed <i>and
1042 *             selected</i>, there are two ways to handle this.  If <i>all</i> of your suggestions
1043 *             can handle the action key, you can simply define the action message using this
1044 *             attribute.  This will be added to the
1045 *             {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} intent that is passed to
1046 *             your searchable activity.  To examine the string, use
1047 *             {@link android.content.Intent#getStringExtra
1048 *             getStringExtra(SearchManager.ACTION_MSG)}.</td>
1049 *         <td align="center">No</td>
1050 *     </tr>
1051 *
1052 *     <tr><th>android:suggestActionMsgColumn</th>
1053 *         <td>If you wish to handle an action key while a suggestion is being displayed <i>and
1054 *             selected</i>, but you do not wish to enable this action key for every suggestion,
1055 *             then you can use this attribute to control it on a suggestion-by-suggestion basis.
1056 *             First, you must define a column (and name it here) where your suggestions will
1057 *             include the action string.  Then, in your content provider, you must provide this
1058 *             column, and when desired, provide data in this column.
1059 *             The search manager will look at your suggestion cursor, using the string
1060 *             provided here in order to select a column, and will use that to select a string from
1061 *             the cursor.  That string will be added to the
1062 *             {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} intent that is passed to
1063 *             your searchable activity.  To examine the string, use
1064 *             {@link android.content.Intent#getStringExtra
1065 *             getStringExtra(SearchManager.ACTION_MSG)}.  <i>If the data does not exist for the
1066 *             selection suggestion, the action key will be ignored.</i></td>
1067 *         <td align="center">No</td>
1068 *     </tr>
1069 *
1070 *     </tbody>
1071 * </table>
1072 *
1073 * <p><b>Additional metadata for enabling voice search.</b>  To enable voice search for your
1074 * activity, you can add fields to the metadata that enable and configure voice search.  When
1075 * enabled (and available on the device), a voice search button will be displayed in the
1076 * Search UI.  Clicking this button will launch a voice search activity.  When the user has
1077 * finished speaking, the voice search phrase will be transcribed into text and presented to the
1078 * searchable activity as if it were a typed query.
1079 *
1080 * <p>Elements of search metadata that support voice search:
1081 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
1082 *
1083 *     <thead>
1084 *     <tr><th>Attribute</th> <th>Description</th> <th>Required?</th></tr>
1085 *     </thead>
1086 *
1087 *     <tr><th>android:voiceSearchMode</th>
1088 *         <td>If provided and non-zero, enables voice search.  (Voice search may not be
1089 *             provided by the device, in which case these flags will have no effect.)  The
1090 *             following mode bits are defined:
1091 *             <table border="2" align="center" frame="hsides" rules="rows">
1092 *                 <tbody>
1093 *                 <tr><th>showVoiceSearchButton</th>
1094 *                     <td>If set, display a voice search button.  This only takes effect if voice
1095 *                         search is available on the device.  If set, then launchWebSearch or
1096 *                         launchRecognizer must also be set.</td>
1097 *                 </tr>
1098 *                 <tr><th>launchWebSearch</th>
1099 *                     <td>If set, the voice search button will take the user directly to a
1100 *                         built-in voice web search activity.  Most applications will not use this
1101 *                         flag, as it will take the user away from the activity in which search
1102 *                         was invoked.</td>
1103 *                 </tr>
1104 *                 <tr><th>launchRecognizer</th>
1105 *                     <td>If set, the voice search button will take the user directly to a
1106 *                         built-in voice recording activity.  This activity will prompt the user
1107 *                         to speak, transcribe the spoken text, and forward the resulting query
1108 *                         text to the searchable activity, just as if the user had typed it into
1109 *                         the search UI and clicked the search button.</td>
1110 *                 </tr>
1111 *                 </tbody>
1112 *            </table></td>
1113 *         <td align="center">No</td>
1114 *     </tr>
1115 *
1116 *     <tr><th>android:voiceLanguageModel</th>
1117 *         <td>If provided, this specifies the language model that should be used by the voice
1118 *             recognition system.
1119 *             See {@link android.speech.RecognizerIntent#EXTRA_LANGUAGE_MODEL}
1120 *             for more information.  If not provided, the default value
1121 *             {@link android.speech.RecognizerIntent#LANGUAGE_MODEL_FREE_FORM} will be used.</td>
1122 *         <td align="center">No</td>
1123 *     </tr>
1124 *
1125 *     <tr><th>android:voicePromptText</th>
1126 *         <td>If provided, this specifies a prompt that will be displayed during voice input.
1127 *             (If not provided, a default prompt will be displayed.)</td>
1128 *         <td align="center">No</td>
1129 *     </tr>
1130 *
1131 *     <tr><th>android:voiceLanguage</th>
1132 *         <td>If provided, this specifies the spoken language to be expected.  This is only
1133 *             needed if it is different from the current value of
1134 *             {@link java.util.Locale#getDefault()}.
1135 *             </td>
1136 *         <td align="center">No</td>
1137 *     </tr>
1138 *
1139 *     <tr><th>android:voiceMaxResults</th>
1140 *         <td>If provided, enforces the maximum number of results to return, including the "best"
1141 *             result which will always be provided as the SEARCH intent's primary query.  Must be
1142 *             one or greater.  Use {@link android.speech.RecognizerIntent#EXTRA_RESULTS}
1143 *             to get the results from the intent.  If not provided, the recognizer will choose
1144 *             how many results to return.</td>
1145 *         <td align="center">No</td>
1146 *     </tr>
1147 *
1148 *     </tbody>
1149 * </table>
1150 *
1151 * <a name="PassingSearchContext"></a>
1152 * <h3>Passing Search Context</h3>
1153 *
1154 * <p>In order to improve search experience, an application may wish to specify
1155 * additional data along with the search, such as local history or context.  For
1156 * example, a maps search would be improved by including the current location.
1157 * In order to simplify the structure of your activities, this can be done using
1158 * the search manager.
1159 *
1160 * <p>Any data can be provided at the time the search is launched, as long as it
1161 * can be stored in a {@link android.os.Bundle Bundle} object.
1162 *
1163 * <p>To pass application data into the Search Manager, you'll need to override
1164 * {@link android.app.Activity#onSearchRequested onSearchRequested} as follows:
1165 *
1166 * <pre class="prettyprint">
1167 * &#64;Override
1168 * public boolean onSearchRequested() {
1169 *     Bundle appData = new Bundle();
1170 *     appData.put...();
1171 *     appData.put...();
1172 *     startSearch(null, false, appData, false);
1173 *     return true;
1174 * }</pre>
1175 *
1176 * <p>To receive application data from the Search Manager, you'll extract it from
1177 * the {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}
1178 * {@link android.content.Intent Intent} as follows:
1179 *
1180 * <pre class="prettyprint">
1181 * final Bundle appData = queryIntent.getBundleExtra(SearchManager.APP_DATA);
1182 * if (appData != null) {
1183 *     appData.get...();
1184 *     appData.get...();
1185 * }</pre>
1186 *
1187 * <a name="ProtectingUserPrivacy"></a>
1188 * <h3>Protecting User Privacy</h3>
1189 *
1190 * <p>Many users consider their activities on the phone, including searches, to be private
1191 * information.  Applications that implement search should take steps to protect users' privacy
1192 * wherever possible.  This section covers two areas of concern, but you should consider your search
1193 * design carefully and take any additional steps necessary.
1194 *
1195 * <p><b>Don't send personal information to servers, and if you do, don't log it.</b>
1196 * "Personal information" is information that can personally identify your users, such as name,
1197 * email address or billing information, or other data which can be reasonably linked to such
1198 * information.  If your application implements search with the assistance of a server, try to
1199 * avoid sending personal information with your searches.  For example, if you are searching for
1200 * businesses near a zip code, you don't need to send the user ID as well - just send the zip code
1201 * to the server.  If you do need to send personal information, you should take steps to avoid
1202 * logging it.  If you must log it, you should protect that data very carefully, and erase it as
1203 * soon as possible.
1204 *
1205 * <p><b>Provide the user with a way to clear their search history.</b>  The Search Manager helps
1206 * your application provide context-specific suggestions.  Sometimes these suggestions are based
1207 * on previous searches, or other actions taken by the user in an earlier session.  A user may not
1208 * wish for previous searches to be revealed to other users, for instance if they share their phone
1209 * with a friend.  If your application provides suggestions that can reveal previous activities,
1210 * you should implement a "Clear History" menu, preference, or button.  If you are using
1211 * {@link android.provider.SearchRecentSuggestions}, you can simply call its
1212 * {@link android.provider.SearchRecentSuggestions#clearHistory() clearHistory()} method from
1213 * your "Clear History" UI.  If you are implementing your own form of recent suggestions, you'll
1214 * need to provide a similar a "clear history" API in your provider, and call it from your
1215 * "Clear History" UI.
1216 */
1217public class SearchManager
1218        implements DialogInterface.OnDismissListener, DialogInterface.OnCancelListener
1219{
1220
1221    private static final boolean DBG = false;
1222    private static final String TAG = "SearchManager";
1223
1224    /**
1225     * This is a shortcut definition for the default menu key to use for invoking search.
1226     *
1227     * See Menu.Item.setAlphabeticShortcut() for more information.
1228     */
1229    public final static char MENU_KEY = 's';
1230
1231    /**
1232     * This is a shortcut definition for the default menu key to use for invoking search.
1233     *
1234     * See Menu.Item.setAlphabeticShortcut() for more information.
1235     */
1236    public final static int MENU_KEYCODE = KeyEvent.KEYCODE_S;
1237
1238    /**
1239     * Intent extra data key: Use this key with
1240     * {@link android.content.Intent#getStringExtra
1241     *  content.Intent.getStringExtra()}
1242     * to obtain the query string from Intent.ACTION_SEARCH.
1243     */
1244    public final static String QUERY = "query";
1245
1246    /**
1247     * Intent extra data key: Use this key with
1248     * {@link android.content.Intent#getStringExtra
1249     *  content.Intent.getStringExtra()}
1250     * to obtain the query string typed in by the user.
1251     * This may be different from the value of {@link #QUERY}
1252     * if the intent is the result of selecting a suggestion.
1253     * In that case, {@link #QUERY} will contain the value of
1254     * {@link #SUGGEST_COLUMN_QUERY} for the suggestion, and
1255     * {@link #USER_QUERY} will contain the string typed by the
1256     * user.
1257     */
1258    public final static String USER_QUERY = "user_query";
1259
1260    /**
1261     * Intent extra data key: Use this key with Intent.ACTION_SEARCH and
1262     * {@link android.content.Intent#getBundleExtra
1263     *  content.Intent.getBundleExtra()}
1264     * to obtain any additional app-specific data that was inserted by the
1265     * activity that launched the search.
1266     */
1267    public final static String APP_DATA = "app_data";
1268
1269    /**
1270     * Intent extra data key: Use {@link android.content.Intent#getBundleExtra
1271     * content.Intent.getBundleExtra(SEARCH_MODE)} to get the search mode used
1272     * to launch the intent.
1273     * The only current value for this is {@link #MODE_GLOBAL_SEARCH_SUGGESTION}.
1274     *
1275     * @hide
1276     */
1277    public final static String SEARCH_MODE = "search_mode";
1278
1279    /**
1280     * Intent extra data key: Use this key with Intent.ACTION_SEARCH and
1281     * {@link android.content.Intent#getIntExtra content.Intent.getIntExtra()}
1282     * to obtain the keycode that the user used to trigger this query.  It will be zero if the
1283     * user simply pressed the "GO" button on the search UI.  This is primarily used in conjunction
1284     * with the keycode attribute in the actionkey element of your searchable.xml configuration
1285     * file.
1286     */
1287    public final static String ACTION_KEY = "action_key";
1288
1289    /**
1290     * Intent extra data key: This key will be used for the extra populated by the
1291     * {@link #SUGGEST_COLUMN_INTENT_EXTRA_DATA} column.
1292     */
1293    public final static String EXTRA_DATA_KEY = "intent_extra_data_key";
1294
1295    /**
1296     * Boolean extra data key for {@link #INTENT_ACTION_GLOBAL_SEARCH} intents. If {@code true},
1297     * the initial query should be selected when the global search activity is started, so
1298     * that the user can easily replace it with another query.
1299     */
1300    public final static String EXTRA_SELECT_QUERY = "select_query";
1301
1302    /**
1303     * Intent extra data key: Use this key with Intent.ACTION_SEARCH and
1304     * {@link android.content.Intent#getStringExtra content.Intent.getStringExtra()}
1305     * to obtain the action message that was defined for a particular search action key and/or
1306     * suggestion.  It will be null if the search was launched by typing "enter", touched the the
1307     * "GO" button, or other means not involving any action key.
1308     */
1309    public final static String ACTION_MSG = "action_msg";
1310
1311    /**
1312     * Uri path for queried suggestions data.  This is the path that the search manager
1313     * will use when querying your content provider for suggestions data based on user input
1314     * (e.g. looking for partial matches).
1315     * Typically you'll use this with a URI matcher.
1316     */
1317    public final static String SUGGEST_URI_PATH_QUERY = "search_suggest_query";
1318
1319    /**
1320     * MIME type for suggestions data.  You'll use this in your suggestions content provider
1321     * in the getType() function.
1322     */
1323    public final static String SUGGEST_MIME_TYPE =
1324            "vnd.android.cursor.dir/vnd.android.search.suggest";
1325
1326    /**
1327     * Uri path for shortcut validation.  This is the path that the search manager will use when
1328     * querying your content provider to refresh a shortcutted suggestion result and to check if it
1329     * is still valid.  When asked, a source may return an up to date result, or no result.  No
1330     * result indicates the shortcut refers to a no longer valid sugggestion.
1331     *
1332     * @see #SUGGEST_COLUMN_SHORTCUT_ID
1333     */
1334    public final static String SUGGEST_URI_PATH_SHORTCUT = "search_suggest_shortcut";
1335
1336    /**
1337     * MIME type for shortcut validation.  You'll use this in your suggestions content provider
1338     * in the getType() function.
1339     */
1340    public final static String SHORTCUT_MIME_TYPE =
1341            "vnd.android.cursor.item/vnd.android.search.suggest";
1342
1343    /**
1344     * Column name for suggestions cursor.  <i>Unused - can be null or column can be omitted.</i>
1345     */
1346    public final static String SUGGEST_COLUMN_FORMAT = "suggest_format";
1347    /**
1348     * Column name for suggestions cursor.  <i>Required.</i>  This is the primary line of text that
1349     * will be presented to the user as the suggestion.
1350     */
1351    public final static String SUGGEST_COLUMN_TEXT_1 = "suggest_text_1";
1352    /**
1353     * Column name for suggestions cursor.  <i>Optional.</i>  If your cursor includes this column,
1354     *  then all suggestions will be provided in a two-line format.  The second line of text is in
1355     *  a much smaller appearance.
1356     */
1357    public final static String SUGGEST_COLUMN_TEXT_2 = "suggest_text_2";
1358    /**
1359     * Column name for suggestions cursor.  <i>Optional.</i>  If your cursor includes this column,
1360     *  then all suggestions will be provided in a format that includes space for two small icons,
1361     *  one at the left and one at the right of each suggestion.  The data in the column must
1362     *  be a resource ID of a drawable, or a URI in one of the following formats:
1363     *
1364     * <ul>
1365     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1366     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1367     * <li>file ({@link android.content.ContentResolver#SCHEME_FILE})</li>
1368     * </ul>
1369     *
1370     * See {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String)}
1371     * for more information on these schemes.
1372     */
1373    public final static String SUGGEST_COLUMN_ICON_1 = "suggest_icon_1";
1374    /**
1375     * Column name for suggestions cursor.  <i>Optional.</i>  If your cursor includes this column,
1376     *  then all suggestions will be provided in a format that includes space for two small icons,
1377     *  one at the left and one at the right of each suggestion.  The data in the column must
1378     *  be a resource ID of a drawable, or a URI in one of the following formats:
1379     *
1380     * <ul>
1381     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1382     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1383     * <li>file ({@link android.content.ContentResolver#SCHEME_FILE})</li>
1384     * </ul>
1385     *
1386     * See {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String)}
1387     * for more information on these schemes.
1388     */
1389    public final static String SUGGEST_COLUMN_ICON_2 = "suggest_icon_2";
1390    /**
1391     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
1392     * this element exists at the given row, this is the action that will be used when
1393     * forming the suggestion's intent.  If the element is not provided, the action will be taken
1394     * from the android:searchSuggestIntentAction field in your XML metadata.  <i>At least one of
1395     * these must be present for the suggestion to generate an intent.</i>  Note:  If your action is
1396     * the same for all suggestions, it is more efficient to specify it using XML metadata and omit
1397     * it from the cursor.
1398     */
1399    public final static String SUGGEST_COLUMN_INTENT_ACTION = "suggest_intent_action";
1400    /**
1401     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
1402     * this element exists at the given row, this is the data that will be used when
1403     * forming the suggestion's intent.  If the element is not provided, the data will be taken
1404     * from the android:searchSuggestIntentData field in your XML metadata.  If neither source
1405     * is provided, the Intent's data field will be null.  Note:  If your data is
1406     * the same for all suggestions, or can be described using a constant part and a specific ID,
1407     * it is more efficient to specify it using XML metadata and omit it from the cursor.
1408     */
1409    public final static String SUGGEST_COLUMN_INTENT_DATA = "suggest_intent_data";
1410    /**
1411     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
1412     * this element exists at the given row, this is the data that will be used when
1413     * forming the suggestion's intent. If not provided, the Intent's extra data field will be null.
1414     * This column allows suggestions to provide additional arbitrary data which will be included as
1415     * an extra under the key {@link #EXTRA_DATA_KEY}.
1416     */
1417    public final static String SUGGEST_COLUMN_INTENT_EXTRA_DATA = "suggest_intent_extra_data";
1418    /**
1419     * TODO: Remove
1420     *
1421     * @hide
1422     */
1423    public final static String SUGGEST_COLUMN_INTENT_COMPONENT_NAME = "suggest_intent_component";
1424    /**
1425     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
1426     * this element exists at the given row, then "/" and this value will be appended to the data
1427     * field in the Intent.  This should only be used if the data field has already been set to an
1428     * appropriate base string.
1429     */
1430    public final static String SUGGEST_COLUMN_INTENT_DATA_ID = "suggest_intent_data_id";
1431    /**
1432     * Column name for suggestions cursor.  <i>Required if action is
1433     * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}, optional otherwise.</i>  If this
1434     * column exists <i>and</i> this element exists at the given row, this is the data that will be
1435     * used when forming the suggestion's query.
1436     */
1437    public final static String SUGGEST_COLUMN_QUERY = "suggest_intent_query";
1438
1439    /**
1440     * Column name for suggestions cursor. <i>Optional.</i>  This column is used to indicate whether
1441     * a search suggestion should be stored as a shortcut, and whether it should be refreshed.  If
1442     * missing, the result will be stored as a shortcut and never validated.  If set to
1443     * {@link #SUGGEST_NEVER_MAKE_SHORTCUT}, the result will not be stored as a shortcut.
1444     * Otherwise, the shortcut id will be used to check back for an up to date suggestion using
1445     * {@link #SUGGEST_URI_PATH_SHORTCUT}.
1446     */
1447    public final static String SUGGEST_COLUMN_SHORTCUT_ID = "suggest_shortcut_id";
1448
1449    /**
1450     * Column name for suggestions cursor. <i>Optional.</i>  This column is used to specify the
1451     * cursor item's background color if it needs a non-default background color. A non-zero value
1452     * indicates a valid background color to override the default.
1453     *
1454     * @hide For internal use, not part of the public API.
1455     */
1456    public final static String SUGGEST_COLUMN_BACKGROUND_COLOR = "suggest_background_color";
1457
1458    /**
1459     * Column name for suggestions cursor. <i>Optional.</i> This column is used to specify
1460     * that a spinner should be shown in lieu of an icon2 while the shortcut of this suggestion
1461     * is being refreshed.
1462     */
1463    public final static String SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING =
1464            "suggest_spinner_while_refreshing";
1465
1466    /**
1467     * Column value for suggestion column {@link #SUGGEST_COLUMN_SHORTCUT_ID} when a suggestion
1468     * should not be stored as a shortcut in global search.
1469     */
1470    public final static String SUGGEST_NEVER_MAKE_SHORTCUT = "_-1";
1471
1472    /**
1473     * Query parameter added to suggestion queries to limit the number of suggestions returned.
1474     * This limit is only advisory and suggestion providers may chose to ignore it.
1475     */
1476    public final static String SUGGEST_PARAMETER_LIMIT = "limit";
1477
1478    /**
1479     * Intent action for starting the global search activity.
1480     * The global search provider should handle this intent.
1481     *
1482     * Supported extra data keys: {@link #QUERY},
1483     * {@link #EXTRA_SELECT_QUERY},
1484     * {@link #APP_DATA}.
1485     */
1486    public final static String INTENT_ACTION_GLOBAL_SEARCH
1487            = "android.search.action.GLOBAL_SEARCH";
1488
1489    /**
1490     * Intent action for starting the global search settings activity.
1491     * The global search provider should handle this intent.
1492     */
1493    public final static String INTENT_ACTION_SEARCH_SETTINGS
1494            = "android.search.action.SEARCH_SETTINGS";
1495
1496    /**
1497     * Intent action for starting a web search provider's settings activity.
1498     * Web search providers should handle this intent if they have provider-specific
1499     * settings to implement.
1500     */
1501    public final static String INTENT_ACTION_WEB_SEARCH_SETTINGS
1502            = "android.search.action.WEB_SEARCH_SETTINGS";
1503
1504    /**
1505     * Intent action broadcasted to inform that the searchables list or default have changed.
1506     * Components should handle this intent if they cache any searchable data and wish to stay
1507     * up to date on changes.
1508     */
1509    public final static String INTENT_ACTION_SEARCHABLES_CHANGED
1510            = "android.search.action.SEARCHABLES_CHANGED";
1511
1512    /**
1513     * Intent action broadcasted to inform that the search settings have changed in some way.
1514     * Either searchables have been enabled or disabled, or a different web search provider
1515     * has been chosen.
1516     */
1517    public final static String INTENT_ACTION_SEARCH_SETTINGS_CHANGED
1518            = "android.search.action.SETTINGS_CHANGED";
1519
1520    /**
1521     * If a suggestion has this value in {@link #SUGGEST_COLUMN_INTENT_ACTION},
1522     * the search dialog will take no action.
1523     *
1524     * @hide
1525     */
1526    public final static String INTENT_ACTION_NONE = "android.search.action.ZILCH";
1527
1528    /**
1529     * Reference to the shared system search service.
1530     */
1531    private static ISearchManager mService;
1532
1533    private final Context mContext;
1534
1535    /**
1536     * The package associated with this seach manager.
1537     */
1538    private String mAssociatedPackage;
1539
1540    // package private since they are used by the inner class SearchManagerCallback
1541    /* package */ final Handler mHandler;
1542    /* package */ OnDismissListener mDismissListener = null;
1543    /* package */ OnCancelListener mCancelListener = null;
1544
1545    private SearchDialog mSearchDialog;
1546
1547    /*package*/ SearchManager(Context context, Handler handler)  {
1548        mContext = context;
1549        mHandler = handler;
1550        mService = ISearchManager.Stub.asInterface(
1551                ServiceManager.getService(Context.SEARCH_SERVICE));
1552    }
1553
1554    /**
1555     * Launch search UI.
1556     *
1557     * <p>The search manager will open a search widget in an overlapping
1558     * window, and the underlying activity may be obscured.  The search
1559     * entry state will remain in effect until one of the following events:
1560     * <ul>
1561     * <li>The user completes the search.  In most cases this will launch
1562     * a search intent.</li>
1563     * <li>The user uses the back, home, or other keys to exit the search.</li>
1564     * <li>The application calls the {@link #stopSearch}
1565     * method, which will hide the search window and return focus to the
1566     * activity from which it was launched.</li>
1567     *
1568     * <p>Most applications will <i>not</i> use this interface to invoke search.
1569     * The primary method for invoking search is to call
1570     * {@link android.app.Activity#onSearchRequested Activity.onSearchRequested()} or
1571     * {@link android.app.Activity#startSearch Activity.startSearch()}.
1572     *
1573     * @param initialQuery A search string can be pre-entered here, but this
1574     * is typically null or empty.
1575     * @param selectInitialQuery If true, the intial query will be preselected, which means that
1576     * any further typing will replace it.  This is useful for cases where an entire pre-formed
1577     * query is being inserted.  If false, the selection point will be placed at the end of the
1578     * inserted query.  This is useful when the inserted query is text that the user entered,
1579     * and the user would expect to be able to keep typing.  <i>This parameter is only meaningful
1580     * if initialQuery is a non-empty string.</i>
1581     * @param launchActivity The ComponentName of the activity that has launched this search.
1582     * @param appSearchData An application can insert application-specific
1583     * context here, in order to improve quality or specificity of its own
1584     * searches.  This data will be returned with SEARCH intent(s).  Null if
1585     * no extra data is required.
1586     * @param globalSearch If false, this will only launch the search that has been specifically
1587     * defined by the application (which is usually defined as a local search).  If no default
1588     * search is defined in the current application or activity, global search will be launched.
1589     * If true, this will always launch a platform-global (e.g. web-based) search instead.
1590     *
1591     * @see android.app.Activity#onSearchRequested
1592     * @see #stopSearch
1593     */
1594    public void startSearch(String initialQuery,
1595                            boolean selectInitialQuery,
1596                            ComponentName launchActivity,
1597                            Bundle appSearchData,
1598                            boolean globalSearch) {
1599        if (globalSearch) {
1600            startGlobalSearch(initialQuery, selectInitialQuery, appSearchData);
1601            return;
1602        }
1603
1604        ensureSearchDialog();
1605
1606        mSearchDialog.show(initialQuery, selectInitialQuery, launchActivity, appSearchData);
1607    }
1608
1609    private void ensureSearchDialog() {
1610        if (mSearchDialog == null) {
1611            mSearchDialog = new SearchDialog(mContext, this);
1612            mSearchDialog.setOnCancelListener(this);
1613            mSearchDialog.setOnDismissListener(this);
1614        }
1615    }
1616
1617    /**
1618     * Starts the global search activity.
1619     */
1620    /* package */ void startGlobalSearch(String initialQuery, boolean selectInitialQuery,
1621            Bundle appSearchData) {
1622        ComponentName globalSearchActivity = getGlobalSearchActivity();
1623        if (globalSearchActivity == null) {
1624            Log.w(TAG, "No global search activity found.");
1625            return;
1626        }
1627        Intent intent = new Intent(INTENT_ACTION_GLOBAL_SEARCH);
1628        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1629        intent.setComponent(globalSearchActivity);
1630        // TODO: Always pass name of calling package as an extra?
1631        if (appSearchData != null) {
1632            intent.putExtra(APP_DATA, appSearchData);
1633        }
1634        if (!TextUtils.isEmpty(initialQuery)) {
1635            intent.putExtra(QUERY, initialQuery);
1636        }
1637        if (selectInitialQuery) {
1638            intent.putExtra(EXTRA_SELECT_QUERY, selectInitialQuery);
1639        }
1640        try {
1641            if (DBG) Log.d(TAG, "Starting global search: " + intent.toUri(0));
1642            mContext.startActivity(intent);
1643        } catch (ActivityNotFoundException ex) {
1644            Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
1645        }
1646    }
1647
1648    /**
1649     * Gets the name of the global search activity.
1650     *
1651     * @hide
1652     */
1653    public ComponentName getGlobalSearchActivity() {
1654        try {
1655            return mService.getGlobalSearchActivity();
1656        } catch (RemoteException ex) {
1657            Log.e(TAG, "getGlobalSearchActivity() failed: " + ex);
1658            return null;
1659        }
1660    }
1661
1662    /**
1663     * Gets the name of the web search activity.
1664     *
1665     * @return The name of the default activity for web searches. This activity
1666     *         can be used to get web search suggestions. Returns {@code null} if
1667     *         there is no default web search activity.
1668     *
1669     * @hide
1670     */
1671    public ComponentName getWebSearchActivity() {
1672        try {
1673            return mService.getWebSearchActivity();
1674        } catch (RemoteException ex) {
1675            Log.e(TAG, "getWebSearchActivity() failed: " + ex);
1676            return null;
1677        }
1678    }
1679
1680    /**
1681     * Similar to {@link #startSearch} but actually fires off the search query after invoking
1682     * the search dialog.  Made available for testing purposes.
1683     *
1684     * @param query The query to trigger.  If empty, request will be ignored.
1685     * @param launchActivity The ComponentName of the activity that has launched this search.
1686     * @param appSearchData An application can insert application-specific
1687     * context here, in order to improve quality or specificity of its own
1688     * searches.  This data will be returned with SEARCH intent(s).  Null if
1689     * no extra data is required.
1690     *
1691     * @see #startSearch
1692     */
1693    public void triggerSearch(String query,
1694                              ComponentName launchActivity,
1695                              Bundle appSearchData) {
1696        if (!mAssociatedPackage.equals(launchActivity.getPackageName())) {
1697            throw new IllegalArgumentException("invoking app search on a different package " +
1698                    "not associated with this search manager");
1699        }
1700        if (query == null || TextUtils.getTrimmedLength(query) == 0) {
1701            Log.w(TAG, "triggerSearch called with empty query, ignoring.");
1702            return;
1703        }
1704        startSearch(query, false, launchActivity, appSearchData, false);
1705        mSearchDialog.launchQuerySearch();
1706    }
1707
1708    /**
1709     * Terminate search UI.
1710     *
1711     * <p>Typically the user will terminate the search UI by launching a
1712     * search or by canceling.  This function allows the underlying application
1713     * or activity to cancel the search prematurely (for any reason).
1714     *
1715     * <p>This function can be safely called at any time (even if no search is active.)
1716     *
1717     * @see #startSearch
1718     */
1719    public void stopSearch() {
1720        if (mSearchDialog != null) {
1721            mSearchDialog.cancel();
1722        }
1723    }
1724
1725    /**
1726     * Determine if the Search UI is currently displayed.
1727     *
1728     * This is provided primarily for application test purposes.
1729     *
1730     * @return Returns true if the search UI is currently displayed.
1731     *
1732     * @hide
1733     */
1734    public boolean isVisible() {
1735        return mSearchDialog == null? false : mSearchDialog.isShowing();
1736    }
1737
1738    /**
1739     * See {@link SearchManager#setOnDismissListener} for configuring your activity to monitor
1740     * search UI state.
1741     */
1742    public interface OnDismissListener {
1743        /**
1744         * This method will be called when the search UI is dismissed. To make use of it, you must
1745         * implement this method in your activity, and call
1746         * {@link SearchManager#setOnDismissListener} to register it.
1747         */
1748        public void onDismiss();
1749    }
1750
1751    /**
1752     * See {@link SearchManager#setOnCancelListener} for configuring your activity to monitor
1753     * search UI state.
1754     */
1755    public interface OnCancelListener {
1756        /**
1757         * This method will be called when the search UI is canceled. To make use if it, you must
1758         * implement this method in your activity, and call
1759         * {@link SearchManager#setOnCancelListener} to register it.
1760         */
1761        public void onCancel();
1762    }
1763
1764    /**
1765     * Set or clear the callback that will be invoked whenever the search UI is dismissed.
1766     *
1767     * @param listener The {@link OnDismissListener} to use, or null.
1768     */
1769    public void setOnDismissListener(final OnDismissListener listener) {
1770        mDismissListener = listener;
1771    }
1772
1773    /**
1774     * Set or clear the callback that will be invoked whenever the search UI is canceled.
1775     *
1776     * @param listener The {@link OnCancelListener} to use, or null.
1777     */
1778    public void setOnCancelListener(OnCancelListener listener) {
1779        mCancelListener = listener;
1780    }
1781
1782    /**
1783     * @deprecated This method is an obsolete internal implementation detail. Do not use.
1784     */
1785    @Deprecated
1786    public void onCancel(DialogInterface dialog) {
1787        if (mCancelListener != null) {
1788            mCancelListener.onCancel();
1789        }
1790    }
1791
1792    /**
1793     * @deprecated This method is an obsolete internal implementation detail. Do not use.
1794     */
1795    @Deprecated
1796    public void onDismiss(DialogInterface dialog) {
1797        if (mDismissListener != null) {
1798            mDismissListener.onDismiss();
1799        }
1800    }
1801
1802    /**
1803     * Gets information about a searchable activity.
1804     *
1805     * @param componentName The activity to get searchable information for.
1806     * @return Searchable information, or <code>null</code> if the activity does not
1807     *         exist, or is not searchable.
1808     */
1809    public SearchableInfo getSearchableInfo(ComponentName componentName) {
1810        try {
1811            return mService.getSearchableInfo(componentName);
1812        } catch (RemoteException ex) {
1813            Log.e(TAG, "getSearchableInfo() failed: " + ex);
1814            return null;
1815        }
1816    }
1817
1818    /**
1819     * Gets a cursor with search suggestions.
1820     *
1821     * @param searchable Information about how to get the suggestions.
1822     * @param query The search text entered (so far).
1823     * @return a cursor with suggestions, or <code>null</null> the suggestion query failed.
1824     *
1825     * @hide because SearchableInfo is not part of the API.
1826     */
1827    public Cursor getSuggestions(SearchableInfo searchable, String query) {
1828        return getSuggestions(searchable, query, -1);
1829    }
1830
1831    /**
1832     * Gets a cursor with search suggestions.
1833     *
1834     * @param searchable Information about how to get the suggestions.
1835     * @param query The search text entered (so far).
1836     * @param limit The query limit to pass to the suggestion provider. This is advisory,
1837     *        the returned cursor may contain more rows. Pass {@code -1} for no limit.
1838     * @return a cursor with suggestions, or <code>null</null> the suggestion query failed.
1839     *
1840     * @hide because SearchableInfo is not part of the API.
1841     */
1842    public Cursor getSuggestions(SearchableInfo searchable, String query, int limit) {
1843        if (searchable == null) {
1844            return null;
1845        }
1846
1847        String authority = searchable.getSuggestAuthority();
1848        if (authority == null) {
1849            return null;
1850        }
1851
1852        Uri.Builder uriBuilder = new Uri.Builder()
1853                .scheme(ContentResolver.SCHEME_CONTENT)
1854                .authority(authority)
1855                .query("")  // TODO: Remove, workaround for a bug in Uri.writeToParcel()
1856                .fragment("");  // TODO: Remove, workaround for a bug in Uri.writeToParcel()
1857
1858        // if content path provided, insert it now
1859        final String contentPath = searchable.getSuggestPath();
1860        if (contentPath != null) {
1861            uriBuilder.appendEncodedPath(contentPath);
1862        }
1863
1864        // append standard suggestion query path
1865        uriBuilder.appendPath(SearchManager.SUGGEST_URI_PATH_QUERY);
1866
1867        // get the query selection, may be null
1868        String selection = searchable.getSuggestSelection();
1869        // inject query, either as selection args or inline
1870        String[] selArgs = null;
1871        if (selection != null) {    // use selection if provided
1872            selArgs = new String[] { query };
1873        } else {                    // no selection, use REST pattern
1874            uriBuilder.appendPath(query);
1875        }
1876
1877        if (limit > 0) {
1878            uriBuilder.appendQueryParameter(SUGGEST_PARAMETER_LIMIT, String.valueOf(limit));
1879        }
1880
1881        Uri uri = uriBuilder.build();
1882
1883        // finally, make the query
1884        return mContext.getContentResolver().query(uri, null, selection, selArgs, null);
1885    }
1886
1887    /**
1888     * Returns a list of the searchable activities that can be included in global search.
1889     *
1890     * @return a list containing searchable information for all searchable activities
1891     *         that have the <code>android:includeInGlobalSearch</code> attribute set
1892     *         in their searchable meta-data.
1893     */
1894    public List<SearchableInfo> getSearchablesInGlobalSearch() {
1895        try {
1896            return mService.getSearchablesInGlobalSearch();
1897        } catch (RemoteException e) {
1898            Log.e(TAG, "getSearchablesInGlobalSearch() failed: " + e);
1899            return null;
1900        }
1901    }
1902
1903}
1904