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