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