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