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