SearchManager.java revision 050453eaf51bb3a267680dc1db2b53cb2fbfcefc
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.ActivityNotFoundException;
20import android.content.ComponentName;
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.DialogInterface;
24import android.content.Intent;
25import android.content.pm.ResolveInfo;
26import android.database.Cursor;
27import android.graphics.Rect;
28import android.net.Uri;
29import android.os.Bundle;
30import android.os.Handler;
31import android.os.RemoteException;
32import android.os.ServiceManager;
33import android.text.TextUtils;
34import android.util.Log;
35import android.view.KeyEvent;
36
37import java.util.List;
38
39/**
40 * This class provides access to the system search services.
41 *
42 * <p>In practice, you won't interact with this class directly, as search
43 * services are provided through methods in {@link android.app.Activity Activity}
44 * and the {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}
45 * {@link android.content.Intent Intent}.
46 * If you do require direct access to the SearchManager, do not instantiate
47 * this class directly. Instead, retrieve it through
48 * {@link android.content.Context#getSystemService
49 * context.getSystemService(Context.SEARCH_SERVICE)}.
50 *
51 * <div class="special">
52 * <p>For a guide to using the search dialog and adding search
53 * suggestions in your application, see the Dev Guide topic about <strong><a
54 * href="{@docRoot}guide/topics/search/index.html">Search</a></strong>.</p>
55 * </div>
56 */
57public class SearchManager
58        implements DialogInterface.OnDismissListener, DialogInterface.OnCancelListener
59{
60
61    private static final boolean DBG = false;
62    private static final String TAG = "SearchManager";
63
64    /**
65     * This is a shortcut definition for the default menu key to use for invoking search.
66     *
67     * See Menu.Item.setAlphabeticShortcut() for more information.
68     */
69    public final static char MENU_KEY = 's';
70
71    /**
72     * This is a shortcut definition for the default menu key to use for invoking search.
73     *
74     * See Menu.Item.setAlphabeticShortcut() for more information.
75     */
76    public final static int MENU_KEYCODE = KeyEvent.KEYCODE_S;
77
78    /**
79     * Intent extra data key: Use this key with
80     * {@link android.content.Intent#getStringExtra
81     *  content.Intent.getStringExtra()}
82     * to obtain the query string from Intent.ACTION_SEARCH.
83     */
84    public final static String QUERY = "query";
85
86    /**
87     * Intent extra data key: Use this key with
88     * {@link android.content.Intent#getStringExtra
89     *  content.Intent.getStringExtra()}
90     * to obtain the query string typed in by the user.
91     * This may be different from the value of {@link #QUERY}
92     * if the intent is the result of selecting a suggestion.
93     * In that case, {@link #QUERY} will contain the value of
94     * {@link #SUGGEST_COLUMN_QUERY} for the suggestion, and
95     * {@link #USER_QUERY} will contain the string typed by the
96     * user.
97     */
98    public final static String USER_QUERY = "user_query";
99
100    /**
101     * Intent extra data key: Use this key with Intent.ACTION_SEARCH and
102     * {@link android.content.Intent#getBundleExtra
103     *  content.Intent.getBundleExtra()}
104     * to obtain any additional app-specific data that was inserted by the
105     * activity that launched the search.
106     */
107    public final static String APP_DATA = "app_data";
108
109    /**
110     * Intent extra data key: Use {@link android.content.Intent#getBundleExtra
111     * content.Intent.getBundleExtra(SEARCH_MODE)} to get the search mode used
112     * to launch the intent.
113     * The only current value for this is {@link #MODE_GLOBAL_SEARCH_SUGGESTION}.
114     *
115     * @hide
116     */
117    public final static String SEARCH_MODE = "search_mode";
118
119    /**
120     * Intent extra data key: Use this key with Intent.ACTION_SEARCH and
121     * {@link android.content.Intent#getIntExtra content.Intent.getIntExtra()}
122     * to obtain the keycode that the user used to trigger this query.  It will be zero if the
123     * user simply pressed the "GO" button on the search UI.  This is primarily used in conjunction
124     * with the keycode attribute in the actionkey element of your searchable.xml configuration
125     * file.
126     */
127    public final static String ACTION_KEY = "action_key";
128
129    /**
130     * Intent extra data key: This key will be used for the extra populated by the
131     * {@link #SUGGEST_COLUMN_INTENT_EXTRA_DATA} column.
132     */
133    public final static String EXTRA_DATA_KEY = "intent_extra_data_key";
134
135    /**
136     * Boolean extra data key for {@link #INTENT_ACTION_GLOBAL_SEARCH} intents. If {@code true},
137     * the initial query should be selected when the global search activity is started, so
138     * that the user can easily replace it with another query.
139     */
140    public final static String EXTRA_SELECT_QUERY = "select_query";
141
142    /**
143     * Boolean extra data key for {@link Intent#ACTION_WEB_SEARCH} intents.  If {@code true},
144     * this search should open a new browser window, rather than using an existing one.
145     */
146    public final static String EXTRA_NEW_SEARCH = "new_search";
147
148    /**
149     * Extra data key for {@link Intent#ACTION_WEB_SEARCH}. If set, the value must be a
150     * {@link PendingIntent}. The search activity handling the {@link Intent#ACTION_WEB_SEARCH}
151     * intent will fill in and launch the pending intent. The data URI will be filled in with an
152     * http or https URI, and {@link android.provider.Browser#EXTRA_HEADERS} may be filled in.
153     */
154    public static final String EXTRA_WEB_SEARCH_PENDINGINTENT = "web_search_pendingintent";
155
156    /**
157     * Boolean extra data key for a suggestion provider to return in {@link Cursor#getExtras} to
158     * indicate that the search is not complete yet. This can be used by the search UI
159     * to indicate that a search is in progress. The suggestion provider can return partial results
160     * this way and send a change notification on the cursor when more results are available.
161     */
162    public final static String CURSOR_EXTRA_KEY_IN_PROGRESS = "in_progress";
163
164    /**
165     * Intent extra data key: Use this key with Intent.ACTION_SEARCH and
166     * {@link android.content.Intent#getStringExtra content.Intent.getStringExtra()}
167     * to obtain the action message that was defined for a particular search action key and/or
168     * suggestion.  It will be null if the search was launched by typing "enter", touched the the
169     * "GO" button, or other means not involving any action key.
170     */
171    public final static String ACTION_MSG = "action_msg";
172
173    /**
174     * Flag to specify that the entry can be used for query refinement, i.e., the query text
175     * in the search field can be replaced with the text in this entry, when a query refinement
176     * icon is clicked. The suggestion list should show such a clickable icon beside the entry.
177     * <p>Use this flag as a bit-field for {@link #SUGGEST_COLUMN_FLAGS}.
178     */
179    public final static int FLAG_QUERY_REFINEMENT = 1 << 0;
180
181    /**
182     * Uri path for queried suggestions data.  This is the path that the search manager
183     * will use when querying your content provider for suggestions data based on user input
184     * (e.g. looking for partial matches).
185     * Typically you'll use this with a URI matcher.
186     */
187    public final static String SUGGEST_URI_PATH_QUERY = "search_suggest_query";
188
189    /**
190     * MIME type for suggestions data.  You'll use this in your suggestions content provider
191     * in the getType() function.
192     */
193    public final static String SUGGEST_MIME_TYPE =
194            "vnd.android.cursor.dir/vnd.android.search.suggest";
195
196    /**
197     * Uri path for shortcut validation.  This is the path that the search manager will use when
198     * querying your content provider to refresh a shortcutted suggestion result and to check if it
199     * is still valid.  When asked, a source may return an up to date result, or no result.  No
200     * result indicates the shortcut refers to a no longer valid sugggestion.
201     *
202     * @see #SUGGEST_COLUMN_SHORTCUT_ID
203     */
204    public final static String SUGGEST_URI_PATH_SHORTCUT = "search_suggest_shortcut";
205
206    /**
207     * MIME type for shortcut validation.  You'll use this in your suggestions content provider
208     * in the getType() function.
209     */
210    public final static String SHORTCUT_MIME_TYPE =
211            "vnd.android.cursor.item/vnd.android.search.suggest";
212
213    /**
214     * Column name for suggestions cursor.  <i>Unused - can be null or column can be omitted.</i>
215     */
216    public final static String SUGGEST_COLUMN_FORMAT = "suggest_format";
217    /**
218     * Column name for suggestions cursor.  <i>Required.</i>  This is the primary line of text that
219     * will be presented to the user as the suggestion.
220     */
221    public final static String SUGGEST_COLUMN_TEXT_1 = "suggest_text_1";
222    /**
223     * Column name for suggestions cursor.  <i>Optional.</i>  If your cursor includes this column,
224     *  then all suggestions will be provided in a two-line format.  The second line of text is in
225     *  a much smaller appearance.
226     */
227    public final static String SUGGEST_COLUMN_TEXT_2 = "suggest_text_2";
228
229    /**
230     * Column name for suggestions cursor.  <i>Optional.</i> This is a URL that will be shown
231     * as the second line of text instead of {@link #SUGGEST_COLUMN_TEXT_2}. This is a separate
232     * column so that the search UI knows to display the text as a URL, e.g. by using a different
233     * color. If this column is absent, or has the value {@code null},
234     * {@link #SUGGEST_COLUMN_TEXT_2} will be used instead.
235     */
236    public final static String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url";
237
238    /**
239     * Column name for suggestions cursor.  <i>Optional.</i>  If your cursor includes this column,
240     *  then all suggestions will be provided in a format that includes space for two small icons,
241     *  one at the left and one at the right of each suggestion.  The data in the column must
242     *  be a resource ID of a drawable, or a URI in one of the following formats:
243     *
244     * <ul>
245     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
246     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
247     * <li>file ({@link android.content.ContentResolver#SCHEME_FILE})</li>
248     * </ul>
249     *
250     * See {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String)}
251     * for more information on these schemes.
252     */
253    public final static String SUGGEST_COLUMN_ICON_1 = "suggest_icon_1";
254    /**
255     * Column name for suggestions cursor.  <i>Optional.</i>  If your cursor includes this column,
256     *  then all suggestions will be provided in a format that includes space for two small icons,
257     *  one at the left and one at the right of each suggestion.  The data in the column must
258     *  be a resource ID of a drawable, or a URI in one of the following formats:
259     *
260     * <ul>
261     * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
262     * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
263     * <li>file ({@link android.content.ContentResolver#SCHEME_FILE})</li>
264     * </ul>
265     *
266     * See {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String)}
267     * for more information on these schemes.
268     */
269    public final static String SUGGEST_COLUMN_ICON_2 = "suggest_icon_2";
270    /**
271     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
272     * this element exists at the given row, this is the action that will be used when
273     * forming the suggestion's intent.  If the element is not provided, the action will be taken
274     * from the android:searchSuggestIntentAction field in your XML metadata.  <i>At least one of
275     * these must be present for the suggestion to generate an intent.</i>  Note:  If your action is
276     * the same for all suggestions, it is more efficient to specify it using XML metadata and omit
277     * it from the cursor.
278     */
279    public final static String SUGGEST_COLUMN_INTENT_ACTION = "suggest_intent_action";
280    /**
281     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
282     * this element exists at the given row, this is the data that will be used when
283     * forming the suggestion's intent.  If the element is not provided, the data will be taken
284     * from the android:searchSuggestIntentData field in your XML metadata.  If neither source
285     * is provided, the Intent's data field will be null.  Note:  If your data is
286     * the same for all suggestions, or can be described using a constant part and a specific ID,
287     * it is more efficient to specify it using XML metadata and omit it from the cursor.
288     */
289    public final static String SUGGEST_COLUMN_INTENT_DATA = "suggest_intent_data";
290    /**
291     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
292     * this element exists at the given row, this is the data that will be used when
293     * forming the suggestion's intent. If not provided, the Intent's extra data field will be null.
294     * This column allows suggestions to provide additional arbitrary data which will be included as
295     * an extra under the key {@link #EXTRA_DATA_KEY}.
296     */
297    public final static String SUGGEST_COLUMN_INTENT_EXTRA_DATA = "suggest_intent_extra_data";
298    /**
299     * Column name for suggestions cursor.  <i>Optional.</i>  If this column exists <i>and</i>
300     * this element exists at the given row, then "/" and this value will be appended to the data
301     * field in the Intent.  This should only be used if the data field has already been set to an
302     * appropriate base string.
303     */
304    public final static String SUGGEST_COLUMN_INTENT_DATA_ID = "suggest_intent_data_id";
305    /**
306     * Column name for suggestions cursor.  <i>Required if action is
307     * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}, optional otherwise.</i>  If this
308     * column exists <i>and</i> this element exists at the given row, this is the data that will be
309     * used when forming the suggestion's query.
310     */
311    public final static String SUGGEST_COLUMN_QUERY = "suggest_intent_query";
312
313    /**
314     * Column name for suggestions cursor. <i>Optional.</i>  This column is used to indicate whether
315     * a search suggestion should be stored as a shortcut, and whether it should be refreshed.  If
316     * missing, the result will be stored as a shortcut and never validated.  If set to
317     * {@link #SUGGEST_NEVER_MAKE_SHORTCUT}, the result will not be stored as a shortcut.
318     * Otherwise, the shortcut id will be used to check back for an up to date suggestion using
319     * {@link #SUGGEST_URI_PATH_SHORTCUT}.
320     */
321    public final static String SUGGEST_COLUMN_SHORTCUT_ID = "suggest_shortcut_id";
322
323    /**
324     * Column name for suggestions cursor. <i>Optional.</i> This column is used to specify
325     * that a spinner should be shown in lieu of an icon2 while the shortcut of this suggestion
326     * is being refreshed.
327     */
328    public final static String SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING =
329            "suggest_spinner_while_refreshing";
330
331    /**
332     * Column name for suggestions cursor. <i>Optional.</i> This column is used to specify
333     * additional flags per item. Multiple flags can be specified.
334     * <p>
335     * Must be one of {@link #FLAG_QUERY_REFINEMENT} or 0 to indicate no flags.
336     * </p>
337     */
338    public final static String SUGGEST_COLUMN_FLAGS = "suggest_flags";
339
340    /**
341     * Column name for suggestions cursor. <i>Optional.</i> This column may be
342     * used to specify the time in {@link System#currentTimeMillis
343     * System.currentTImeMillis()} (wall time in UTC) when an item was last
344     * accessed within the results-providing application. If set, this may be
345     * used to show more-recently-used items first.
346     */
347    public final static String SUGGEST_COLUMN_LAST_ACCESS_HINT = "suggest_last_access_hint";
348
349    /**
350     * Column value for suggestion column {@link #SUGGEST_COLUMN_SHORTCUT_ID} when a suggestion
351     * should not be stored as a shortcut in global search.
352     */
353    public final static String SUGGEST_NEVER_MAKE_SHORTCUT = "_-1";
354
355    /**
356     * Query parameter added to suggestion queries to limit the number of suggestions returned.
357     * This limit is only advisory and suggestion providers may chose to ignore it.
358     */
359    public final static String SUGGEST_PARAMETER_LIMIT = "limit";
360
361    /**
362     * Intent action for starting the global search activity.
363     * The global search provider should handle this intent.
364     *
365     * Supported extra data keys: {@link #QUERY},
366     * {@link #EXTRA_SELECT_QUERY},
367     * {@link #APP_DATA}.
368     */
369    public final static String INTENT_ACTION_GLOBAL_SEARCH
370            = "android.search.action.GLOBAL_SEARCH";
371
372    /**
373     * Intent action for starting the global search settings activity.
374     * The global search provider should handle this intent.
375     */
376    public final static String INTENT_ACTION_SEARCH_SETTINGS
377            = "android.search.action.SEARCH_SETTINGS";
378
379    /**
380     * Intent action for starting a web search provider's settings activity.
381     * Web search providers should handle this intent if they have provider-specific
382     * settings to implement.
383     */
384    public final static String INTENT_ACTION_WEB_SEARCH_SETTINGS
385            = "android.search.action.WEB_SEARCH_SETTINGS";
386
387    /**
388     * Intent action broadcasted to inform that the searchables list or default have changed.
389     * Components should handle this intent if they cache any searchable data and wish to stay
390     * up to date on changes.
391     */
392    public final static String INTENT_ACTION_SEARCHABLES_CHANGED
393            = "android.search.action.SEARCHABLES_CHANGED";
394
395    /**
396     * Intent action to be broadcast to inform that the global search provider
397     * has changed. Normal components will have no need to handle this intent since
398     * they should be using API methods from this class to access the global search
399     * activity
400     *
401     * @hide
402     */
403    public final static String INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED
404            = "android.search.action.GLOBAL_SEARCH_ACTIVITY_CHANGED";
405
406    /**
407     * Intent action broadcasted to inform that the search settings have changed in some way.
408     * Either searchables have been enabled or disabled, or a different web search provider
409     * has been chosen.
410     */
411    public final static String INTENT_ACTION_SEARCH_SETTINGS_CHANGED
412            = "android.search.action.SETTINGS_CHANGED";
413
414    /**
415     * This means that context is voice, and therefore the SearchDialog should
416     * continue showing the microphone until the user indicates that he/she does
417     * not want to re-speak (e.g. by typing).
418     *
419     * @hide
420     */
421    public final static String CONTEXT_IS_VOICE = "android.search.CONTEXT_IS_VOICE";
422
423    /**
424     * This means that the voice icon should not be shown at all, because the
425     * current search engine does not support voice search.
426     * @hide
427     */
428    public final static String DISABLE_VOICE_SEARCH
429            = "android.search.DISABLE_VOICE_SEARCH";
430
431    /**
432     * Reference to the shared system search service.
433     */
434    private static ISearchManager mService;
435
436    private final Context mContext;
437
438    /**
439     * The package associated with this seach manager.
440     */
441    private String mAssociatedPackage;
442
443    // package private since they are used by the inner class SearchManagerCallback
444    /* package */ final Handler mHandler;
445    /* package */ OnDismissListener mDismissListener = null;
446    /* package */ OnCancelListener mCancelListener = null;
447
448    private SearchDialog mSearchDialog;
449
450    /*package*/ SearchManager(Context context, Handler handler)  {
451        mContext = context;
452        mHandler = handler;
453        mService = ISearchManager.Stub.asInterface(
454                ServiceManager.getService(Context.SEARCH_SERVICE));
455    }
456
457    /**
458     * Launch search UI.
459     *
460     * <p>The search manager will open a search widget in an overlapping
461     * window, and the underlying activity may be obscured.  The search
462     * entry state will remain in effect until one of the following events:
463     * <ul>
464     * <li>The user completes the search.  In most cases this will launch
465     * a search intent.</li>
466     * <li>The user uses the back, home, or other keys to exit the search.</li>
467     * <li>The application calls the {@link #stopSearch}
468     * method, which will hide the search window and return focus to the
469     * activity from which it was launched.</li>
470     *
471     * <p>Most applications will <i>not</i> use this interface to invoke search.
472     * The primary method for invoking search is to call
473     * {@link android.app.Activity#onSearchRequested Activity.onSearchRequested()} or
474     * {@link android.app.Activity#startSearch Activity.startSearch()}.
475     *
476     * @param initialQuery A search string can be pre-entered here, but this
477     * is typically null or empty.
478     * @param selectInitialQuery If true, the intial query will be preselected, which means that
479     * any further typing will replace it.  This is useful for cases where an entire pre-formed
480     * query is being inserted.  If false, the selection point will be placed at the end of the
481     * inserted query.  This is useful when the inserted query is text that the user entered,
482     * and the user would expect to be able to keep typing.  <i>This parameter is only meaningful
483     * if initialQuery is a non-empty string.</i>
484     * @param launchActivity The ComponentName of the activity that has launched this search.
485     * @param appSearchData An application can insert application-specific
486     * context here, in order to improve quality or specificity of its own
487     * searches.  This data will be returned with SEARCH intent(s).  Null if
488     * no extra data is required.
489     * @param globalSearch If false, this will only launch the search that has been specifically
490     * defined by the application (which is usually defined as a local search).  If no default
491     * search is defined in the current application or activity, global search will be launched.
492     * If true, this will always launch a platform-global (e.g. web-based) search instead.
493     *
494     * @see android.app.Activity#onSearchRequested
495     * @see #stopSearch
496     */
497    public void startSearch(String initialQuery,
498                            boolean selectInitialQuery,
499                            ComponentName launchActivity,
500                            Bundle appSearchData,
501                            boolean globalSearch) {
502        startSearch(initialQuery, selectInitialQuery, launchActivity,
503                appSearchData, globalSearch, null);
504    }
505
506    /**
507     * As {@link #startSearch(String, boolean, ComponentName, Bundle, boolean)} but including
508     * source bounds for the global search intent.
509     *
510     * @hide
511     */
512    public void startSearch(String initialQuery,
513                            boolean selectInitialQuery,
514                            ComponentName launchActivity,
515                            Bundle appSearchData,
516                            boolean globalSearch,
517                            Rect sourceBounds) {
518        if (globalSearch) {
519            startGlobalSearch(initialQuery, selectInitialQuery, appSearchData, sourceBounds);
520            return;
521        }
522
523        ensureSearchDialog();
524
525        mSearchDialog.show(initialQuery, selectInitialQuery, launchActivity, appSearchData);
526    }
527
528    private void ensureSearchDialog() {
529        if (mSearchDialog == null) {
530            mSearchDialog = new SearchDialog(mContext, this);
531            mSearchDialog.setOnCancelListener(this);
532            mSearchDialog.setOnDismissListener(this);
533        }
534    }
535
536    /**
537     * Starts the global search activity.
538     */
539    /* package */ void startGlobalSearch(String initialQuery, boolean selectInitialQuery,
540            Bundle appSearchData, Rect sourceBounds) {
541        ComponentName globalSearchActivity = getGlobalSearchActivity();
542        if (globalSearchActivity == null) {
543            Log.w(TAG, "No global search activity found.");
544            return;
545        }
546        Intent intent = new Intent(INTENT_ACTION_GLOBAL_SEARCH);
547        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
548        intent.setComponent(globalSearchActivity);
549        // Make sure that we have a Bundle to put source in
550        if (appSearchData == null) {
551            appSearchData = new Bundle();
552        } else {
553            appSearchData = new Bundle(appSearchData);
554        }
555        // Set source to package name of app that starts global search, if not set already.
556        if (!appSearchData.containsKey("source")) {
557            appSearchData.putString("source", mContext.getPackageName());
558        }
559        intent.putExtra(APP_DATA, appSearchData);
560        if (!TextUtils.isEmpty(initialQuery)) {
561            intent.putExtra(QUERY, initialQuery);
562        }
563        if (selectInitialQuery) {
564            intent.putExtra(EXTRA_SELECT_QUERY, selectInitialQuery);
565        }
566        intent.setSourceBounds(sourceBounds);
567        try {
568            if (DBG) Log.d(TAG, "Starting global search: " + intent.toUri(0));
569            mContext.startActivity(intent);
570        } catch (ActivityNotFoundException ex) {
571            Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
572        }
573    }
574
575    /**
576     * Returns a list of installed apps that handle the global search
577     * intent.
578     *
579     * @hide
580     */
581    public List<ResolveInfo> getGlobalSearchActivities() {
582        try {
583            return mService.getGlobalSearchActivities();
584        } catch (RemoteException ex) {
585            Log.e(TAG, "getGlobalSearchActivities() failed: " + ex);
586            return null;
587        }
588    }
589
590    /**
591     * Gets the name of the global search activity.
592     *
593     * @hide
594     */
595    public ComponentName getGlobalSearchActivity() {
596        try {
597            return mService.getGlobalSearchActivity();
598        } catch (RemoteException ex) {
599            Log.e(TAG, "getGlobalSearchActivity() failed: " + ex);
600            return null;
601        }
602    }
603
604    /**
605     * Gets the name of the web search activity.
606     *
607     * @return The name of the default activity for web searches. This activity
608     *         can be used to get web search suggestions. Returns {@code null} if
609     *         there is no default web search activity.
610     *
611     * @hide
612     */
613    public ComponentName getWebSearchActivity() {
614        try {
615            return mService.getWebSearchActivity();
616        } catch (RemoteException ex) {
617            Log.e(TAG, "getWebSearchActivity() failed: " + ex);
618            return null;
619        }
620    }
621
622    /**
623     * Similar to {@link #startSearch} but actually fires off the search query after invoking
624     * the search dialog.  Made available for testing purposes.
625     *
626     * @param query The query to trigger.  If empty, request will be ignored.
627     * @param launchActivity The ComponentName of the activity that has launched this search.
628     * @param appSearchData An application can insert application-specific
629     * context here, in order to improve quality or specificity of its own
630     * searches.  This data will be returned with SEARCH intent(s).  Null if
631     * no extra data is required.
632     *
633     * @see #startSearch
634     */
635    public void triggerSearch(String query,
636                              ComponentName launchActivity,
637                              Bundle appSearchData) {
638        if (!mAssociatedPackage.equals(launchActivity.getPackageName())) {
639            throw new IllegalArgumentException("invoking app search on a different package " +
640                    "not associated with this search manager");
641        }
642        if (query == null || TextUtils.getTrimmedLength(query) == 0) {
643            Log.w(TAG, "triggerSearch called with empty query, ignoring.");
644            return;
645        }
646        startSearch(query, false, launchActivity, appSearchData, false);
647        mSearchDialog.launchQuerySearch();
648    }
649
650    /**
651     * Terminate search UI.
652     *
653     * <p>Typically the user will terminate the search UI by launching a
654     * search or by canceling.  This function allows the underlying application
655     * or activity to cancel the search prematurely (for any reason).
656     *
657     * <p>This function can be safely called at any time (even if no search is active.)
658     *
659     * @see #startSearch
660     */
661    public void stopSearch() {
662        if (mSearchDialog != null) {
663            mSearchDialog.cancel();
664        }
665    }
666
667    /**
668     * Determine if the Search UI is currently displayed.
669     *
670     * This is provided primarily for application test purposes.
671     *
672     * @return Returns true if the search UI is currently displayed.
673     *
674     * @hide
675     */
676    public boolean isVisible() {
677        return mSearchDialog == null? false : mSearchDialog.isShowing();
678    }
679
680    /**
681     * See {@link SearchManager#setOnDismissListener} for configuring your activity to monitor
682     * search UI state.
683     */
684    public interface OnDismissListener {
685        /**
686         * This method will be called when the search UI is dismissed. To make use of it, you must
687         * implement this method in your activity, and call
688         * {@link SearchManager#setOnDismissListener} to register it.
689         */
690        public void onDismiss();
691    }
692
693    /**
694     * See {@link SearchManager#setOnCancelListener} for configuring your activity to monitor
695     * search UI state.
696     */
697    public interface OnCancelListener {
698        /**
699         * This method will be called when the search UI is canceled. To make use if it, you must
700         * implement this method in your activity, and call
701         * {@link SearchManager#setOnCancelListener} to register it.
702         */
703        public void onCancel();
704    }
705
706    /**
707     * Set or clear the callback that will be invoked whenever the search UI is dismissed.
708     *
709     * @param listener The {@link OnDismissListener} to use, or null.
710     */
711    public void setOnDismissListener(final OnDismissListener listener) {
712        mDismissListener = listener;
713    }
714
715    /**
716     * Set or clear the callback that will be invoked whenever the search UI is canceled.
717     *
718     * @param listener The {@link OnCancelListener} to use, or null.
719     */
720    public void setOnCancelListener(OnCancelListener listener) {
721        mCancelListener = listener;
722    }
723
724    /**
725     * @deprecated This method is an obsolete internal implementation detail. Do not use.
726     */
727    @Deprecated
728    public void onCancel(DialogInterface dialog) {
729        if (mCancelListener != null) {
730            mCancelListener.onCancel();
731        }
732    }
733
734    /**
735     * @deprecated This method is an obsolete internal implementation detail. Do not use.
736     */
737    @Deprecated
738    public void onDismiss(DialogInterface dialog) {
739        if (mDismissListener != null) {
740            mDismissListener.onDismiss();
741        }
742    }
743
744    /**
745     * Gets information about a searchable activity.
746     *
747     * @param componentName The activity to get searchable information for.
748     * @return Searchable information, or <code>null</code> if the activity does not
749     *         exist, or is not searchable.
750     */
751    public SearchableInfo getSearchableInfo(ComponentName componentName) {
752        try {
753            return mService.getSearchableInfo(componentName);
754        } catch (RemoteException ex) {
755            Log.e(TAG, "getSearchableInfo() failed: " + ex);
756            return null;
757        }
758    }
759
760    /**
761     * Gets a cursor with search suggestions.
762     *
763     * @param searchable Information about how to get the suggestions.
764     * @param query The search text entered (so far).
765     * @return a cursor with suggestions, or <code>null</null> the suggestion query failed.
766     *
767     * @hide because SearchableInfo is not part of the API.
768     */
769    public Cursor getSuggestions(SearchableInfo searchable, String query) {
770        return getSuggestions(searchable, query, -1);
771    }
772
773    /**
774     * Gets a cursor with search suggestions.
775     *
776     * @param searchable Information about how to get the suggestions.
777     * @param query The search text entered (so far).
778     * @param limit The query limit to pass to the suggestion provider. This is advisory,
779     *        the returned cursor may contain more rows. Pass {@code -1} for no limit.
780     * @return a cursor with suggestions, or <code>null</null> the suggestion query failed.
781     *
782     * @hide because SearchableInfo is not part of the API.
783     */
784    public Cursor getSuggestions(SearchableInfo searchable, String query, int limit) {
785        if (searchable == null) {
786            return null;
787        }
788
789        String authority = searchable.getSuggestAuthority();
790        if (authority == null) {
791            return null;
792        }
793
794        Uri.Builder uriBuilder = new Uri.Builder()
795                .scheme(ContentResolver.SCHEME_CONTENT)
796                .authority(authority)
797                .query("")  // TODO: Remove, workaround for a bug in Uri.writeToParcel()
798                .fragment("");  // TODO: Remove, workaround for a bug in Uri.writeToParcel()
799
800        // if content path provided, insert it now
801        final String contentPath = searchable.getSuggestPath();
802        if (contentPath != null) {
803            uriBuilder.appendEncodedPath(contentPath);
804        }
805
806        // append standard suggestion query path
807        uriBuilder.appendPath(SearchManager.SUGGEST_URI_PATH_QUERY);
808
809        // get the query selection, may be null
810        String selection = searchable.getSuggestSelection();
811        // inject query, either as selection args or inline
812        String[] selArgs = null;
813        if (selection != null) {    // use selection if provided
814            selArgs = new String[] { query };
815        } else {                    // no selection, use REST pattern
816            uriBuilder.appendPath(query);
817        }
818
819        if (limit > 0) {
820            uriBuilder.appendQueryParameter(SUGGEST_PARAMETER_LIMIT, String.valueOf(limit));
821        }
822
823        Uri uri = uriBuilder.build();
824
825        // finally, make the query
826        return mContext.getContentResolver().query(uri, null, selection, selArgs, null);
827    }
828
829    /**
830     * Returns a list of the searchable activities that can be included in global search.
831     *
832     * @return a list containing searchable information for all searchable activities
833     *         that have the <code>android:includeInGlobalSearch</code> attribute set
834     *         in their searchable meta-data.
835     */
836    public List<SearchableInfo> getSearchablesInGlobalSearch() {
837        try {
838            return mService.getSearchablesInGlobalSearch();
839        } catch (RemoteException e) {
840            Log.e(TAG, "getSearchablesInGlobalSearch() failed: " + e);
841            return null;
842        }
843    }
844
845}
846