SearchManager.java revision b2b2ac1287bd1ae5042344f11accae7a46149d54
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.app; 18 19import android.content.ActivityNotFoundException; 20import android.content.ComponentName; 21import android.content.ContentResolver; 22import android.content.Context; 23import android.content.DialogInterface; 24import android.content.Intent; 25import android.content.pm.ResolveInfo; 26import android.database.Cursor; 27import android.graphics.Rect; 28import android.net.Uri; 29import android.os.Bundle; 30import android.os.Handler; 31import android.os.RemoteException; 32import android.os.ServiceManager; 33import android.os.UserHandle; 34import android.text.TextUtils; 35import android.util.Log; 36import android.view.KeyEvent; 37 38import java.util.List; 39 40/** 41 * This class provides access to the system search services. 42 * 43 * <p>In practice, you won't interact with this class directly, as search 44 * services are provided through methods in {@link android.app.Activity Activity} 45 * and the {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} 46 * {@link android.content.Intent Intent}. 47 * If you do require direct access to the SearchManager, do not instantiate 48 * this class directly. Instead, retrieve it through 49 * {@link android.content.Context#getSystemService 50 * context.getSystemService(Context.SEARCH_SERVICE)}. 51 * 52 * <div class="special reference"> 53 * <h3>Developer Guides</h3> 54 * <p>For more information about using the search dialog and adding search 55 * suggestions in your application, read the 56 * <a href="{@docRoot}guide/topics/search/index.html">Search</a> developer guide.</p> 57 * </div> 58 */ 59public 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 {@link Intent#ACTION_WEB_SEARCH} intents. If {@code true}, 146 * this search should open a new browser window, rather than using an existing one. 147 */ 148 public final static String EXTRA_NEW_SEARCH = "new_search"; 149 150 /** 151 * Extra data key for {@link Intent#ACTION_WEB_SEARCH}. If set, the value must be a 152 * {@link PendingIntent}. The search activity handling the {@link Intent#ACTION_WEB_SEARCH} 153 * intent will fill in and launch the pending intent. The data URI will be filled in with an 154 * http or https URI, and {@link android.provider.Browser#EXTRA_HEADERS} may be filled in. 155 */ 156 public static final String EXTRA_WEB_SEARCH_PENDINGINTENT = "web_search_pendingintent"; 157 158 /** 159 * Boolean extra data key for a suggestion provider to return in {@link Cursor#getExtras} to 160 * indicate that the search is not complete yet. This can be used by the search UI 161 * to indicate that a search is in progress. The suggestion provider can return partial results 162 * this way and send a change notification on the cursor when more results are available. 163 */ 164 public final static String CURSOR_EXTRA_KEY_IN_PROGRESS = "in_progress"; 165 166 /** 167 * Intent extra data key: Use this key with Intent.ACTION_SEARCH and 168 * {@link android.content.Intent#getStringExtra content.Intent.getStringExtra()} 169 * to obtain the action message that was defined for a particular search action key and/or 170 * suggestion. It will be null if the search was launched by typing "enter", touched the the 171 * "GO" button, or other means not involving any action key. 172 */ 173 public final static String ACTION_MSG = "action_msg"; 174 175 /** 176 * Flag to specify that the entry can be used for query refinement, i.e., the query text 177 * in the search field can be replaced with the text in this entry, when a query refinement 178 * icon is clicked. The suggestion list should show such a clickable icon beside the entry. 179 * <p>Use this flag as a bit-field for {@link #SUGGEST_COLUMN_FLAGS}. 180 */ 181 public final static int FLAG_QUERY_REFINEMENT = 1 << 0; 182 183 /** 184 * Uri path for queried suggestions data. This is the path that the search manager 185 * will use when querying your content provider for suggestions data based on user input 186 * (e.g. looking for partial matches). 187 * Typically you'll use this with a URI matcher. 188 */ 189 public final static String SUGGEST_URI_PATH_QUERY = "search_suggest_query"; 190 191 /** 192 * MIME type for suggestions data. You'll use this in your suggestions content provider 193 * in the getType() function. 194 */ 195 public final static String SUGGEST_MIME_TYPE = 196 "vnd.android.cursor.dir/vnd.android.search.suggest"; 197 198 /** 199 * Uri path for shortcut validation. This is the path that the search manager will use when 200 * querying your content provider to refresh a shortcutted suggestion result and to check if it 201 * is still valid. When asked, a source may return an up to date result, or no result. No 202 * result indicates the shortcut refers to a no longer valid sugggestion. 203 * 204 * @see #SUGGEST_COLUMN_SHORTCUT_ID 205 */ 206 public final static String SUGGEST_URI_PATH_SHORTCUT = "search_suggest_shortcut"; 207 208 /** 209 * MIME type for shortcut validation. You'll use this in your suggestions content provider 210 * in the getType() function. 211 */ 212 public final static String SHORTCUT_MIME_TYPE = 213 "vnd.android.cursor.item/vnd.android.search.suggest"; 214 215 /** 216 * Column name for suggestions cursor. <i>Unused - can be null or column can be omitted.</i> 217 */ 218 public final static String SUGGEST_COLUMN_FORMAT = "suggest_format"; 219 /** 220 * Column name for suggestions cursor. <i>Required.</i> This is the primary line of text that 221 * will be presented to the user as the suggestion. 222 */ 223 public final static String SUGGEST_COLUMN_TEXT_1 = "suggest_text_1"; 224 /** 225 * Column name for suggestions cursor. <i>Optional.</i> If your cursor includes this column, 226 * then all suggestions will be provided in a two-line format. The second line of text is in 227 * a much smaller appearance. 228 */ 229 public final static String SUGGEST_COLUMN_TEXT_2 = "suggest_text_2"; 230 231 /** 232 * Column name for suggestions cursor. <i>Optional.</i> This is a URL that will be shown 233 * as the second line of text instead of {@link #SUGGEST_COLUMN_TEXT_2}. This is a separate 234 * column so that the search UI knows to display the text as a URL, e.g. by using a different 235 * color. If this column is absent, or has the value {@code null}, 236 * {@link #SUGGEST_COLUMN_TEXT_2} will be used instead. 237 */ 238 public final static String SUGGEST_COLUMN_TEXT_2_URL = "suggest_text_2_url"; 239 240 /** 241 * Column name for suggestions cursor. <i>Optional.</i> If your cursor includes this column, 242 * then all suggestions will be provided in a format that includes space for two small icons, 243 * one at the left and one at the right of each suggestion. The data in the column must 244 * be a resource ID of a drawable, or a URI in one of the following formats: 245 * 246 * <ul> 247 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li> 248 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li> 249 * <li>file ({@link android.content.ContentResolver#SCHEME_FILE})</li> 250 * </ul> 251 * 252 * See {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String)} 253 * for more information on these schemes. 254 */ 255 public final static String SUGGEST_COLUMN_ICON_1 = "suggest_icon_1"; 256 257 /** 258 * Column name for suggestions cursor. <i>Optional.</i> If your cursor includes this column, 259 * then all suggestions will be provided in a format that includes space for two small icons, 260 * one at the left and one at the right of each suggestion. The data in the column must 261 * be a resource ID of a drawable, or a URI in one of the following formats: 262 * 263 * <ul> 264 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li> 265 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li> 266 * <li>file ({@link android.content.ContentResolver#SCHEME_FILE})</li> 267 * </ul> 268 * 269 * See {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String)} 270 * for more information on these schemes. 271 */ 272 public final static String SUGGEST_COLUMN_ICON_2 = "suggest_icon_2"; 273 274 /** 275 * Column name for suggestions cursor. <i>Optional.</i> If your cursor includes this column, 276 * then the image will be displayed when forming the suggestion. The suggested dimension for 277 * the image is 270x400 px for portrait mode and 400x225 px for landscape mode. The data in the 278 * column must be a resource ID of a drawable, or a URI in one of the following formats: 279 * 280 * <ul> 281 * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li> 282 * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li> 283 * <li>file ({@link android.content.ContentResolver#SCHEME_FILE})</li> 284 * </ul> 285 * 286 * See {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String)} 287 * for more information on these schemes. 288 */ 289 public final static String SUGGEST_COLUMN_RESULT_CARD_IMAGE = "suggest_result_card_image"; 290 291 /** 292 * Column name for suggestions cursor. <i>Optional.</i> If this column exists <i>and</i> 293 * this element exists at the given row, this is the action that will be used when 294 * forming the suggestion's intent. If the element is not provided, the action will be taken 295 * from the android:searchSuggestIntentAction field in your XML metadata. <i>At least one of 296 * these must be present for the suggestion to generate an intent.</i> Note: If your action is 297 * the same for all suggestions, it is more efficient to specify it using XML metadata and omit 298 * it from the cursor. 299 */ 300 public final static String SUGGEST_COLUMN_INTENT_ACTION = "suggest_intent_action"; 301 302 /** 303 * Column name for suggestions cursor. <i>Optional.</i> If this column exists <i>and</i> 304 * this element exists at the given row, this is the data that will be used when 305 * forming the suggestion's intent. If the element is not provided, the data will be taken 306 * from the android:searchSuggestIntentData field in your XML metadata. If neither source 307 * is provided, the Intent's data field will be null. Note: If your data is 308 * the same for all suggestions, or can be described using a constant part and a specific ID, 309 * it is more efficient to specify it using XML metadata and omit it from the cursor. 310 */ 311 public final static String SUGGEST_COLUMN_INTENT_DATA = "suggest_intent_data"; 312 313 /** 314 * Column name for suggestions cursor. <i>Optional.</i> If this column exists <i>and</i> 315 * this element exists at the given row, this is the data that will be used when 316 * forming the suggestion's intent. If not provided, the Intent's extra data field will be null. 317 * This column allows suggestions to provide additional arbitrary data which will be included as 318 * an extra under the key {@link #EXTRA_DATA_KEY}. 319 */ 320 public final static String SUGGEST_COLUMN_INTENT_EXTRA_DATA = "suggest_intent_extra_data"; 321 322 /** 323 * Column name for suggestions cursor. <i>Optional.</i> If this column exists <i>and</i> 324 * this element exists at the given row, then "/" and this value will be appended to the data 325 * field in the Intent. This should only be used if the data field has already been set to an 326 * appropriate base string. 327 */ 328 public final static String SUGGEST_COLUMN_INTENT_DATA_ID = "suggest_intent_data_id"; 329 330 /** 331 * Column name for suggestions cursor. <i>Required if action is 332 * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH}, optional otherwise.</i> If this 333 * column exists <i>and</i> this element exists at the given row, this is the data that will be 334 * used when forming the suggestion's query. 335 */ 336 public final static String SUGGEST_COLUMN_QUERY = "suggest_intent_query"; 337 338 /** 339 * Column name for suggestions cursor. <i>Optional.</i> This column is used to indicate whether 340 * a search suggestion should be stored as a shortcut, and whether it should be refreshed. If 341 * missing, the result will be stored as a shortcut and never validated. If set to 342 * {@link #SUGGEST_NEVER_MAKE_SHORTCUT}, the result will not be stored as a shortcut. 343 * Otherwise, the shortcut id will be used to check back for an up to date suggestion using 344 * {@link #SUGGEST_URI_PATH_SHORTCUT}. 345 */ 346 public final static String SUGGEST_COLUMN_SHORTCUT_ID = "suggest_shortcut_id"; 347 348 /** 349 * Column name for suggestions cursor. <i>Optional.</i> This column is used to specify 350 * that a spinner should be shown in lieu of an icon2 while the shortcut of this suggestion 351 * is being refreshed. 352 */ 353 public final static String SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING = 354 "suggest_spinner_while_refreshing"; 355 356 /** 357 * Column name for suggestions cursor. <i>Optional.</i> If your content is media type, you 358 * should provide this column so search app could understand more about your content. The data 359 * in the column must specify the MIME type of the content. 360 */ 361 public final static String SUGGEST_COLUMN_CONTENT_TYPE = "suggest_content_type"; 362 363 /** 364 * Column name for suggestions cursor. <i>Optional.</i> If your content is media type, you 365 * should provide this column to specify whether your content is live media such as live video 366 * or live audio. The value in the column is of integer type with value of either 0 indicating 367 * non-live content or 1 indicating live content. 368 */ 369 public final static String SUGGEST_COLUMN_IS_LIVE = "suggest_is_live"; 370 371 /** 372 * Column name for suggestions cursor. <i>Optional.</i> If your content is video, you should 373 * provide this column to specify the number of vertical lines. The data in the column is of 374 * integer type. 375 */ 376 public final static String SUGGEST_COLUMN_VIDEO_WIDTH = "suggest_video_width"; 377 378 /** 379 * Column name for suggestions cursor. <i>Optional.</i> If your content is video, you should 380 * provide this column to specify the number of horizontal lines. The data in the column is of 381 * integer type. 382 */ 383 public final static String SUGGEST_COLUMN_VIDEO_HEIGHT = "suggest_video_height"; 384 385 /** 386 * Column name for suggestions cursor. <i>Optional.</i> If your content contains audio, you 387 * should provide this column to specify the audio channel configuration. The data in the 388 * column is string with format like "channels.subchannels" such as "1.0" or "5.1". 389 */ 390 public final static String SUGGEST_COLUMN_AUDIO_CHANNEL_CONFIG = "suggest_audio_channel_config"; 391 392 /** 393 * Column name for suggestions cursor. <i>Optional.</i> If your content is purchasable, you 394 * should provide this column to specify the displayable string representation of the purchase 395 * price of your content including the currency and the amount. If it's free, you should 396 * provide localized string to specify that it's free. This column can be omitted if the content 397 * is not applicable to purchase. 398 */ 399 public final static String SUGGEST_COLUMN_PURCHASE_PRICE = "suggest_purchase_price"; 400 401 /** 402 * Column name for suggestions cursor. <i>Optional.</i> If your content is rentable, you 403 * should provide this column to specify the displayable string representation of the rental 404 * price of your content including the currency and the amount. If it's free, you should 405 * provide localized string to specify that it's free. This column can be ommitted if the 406 * content is not applicable to rent. 407 */ 408 public final static String SUGGEST_COLUMN_RENTAL_PRICE = "suggest_rental_price"; 409 410 /** 411 * Column name for suggestions cursor. <i>Optional.</i> If your content has a rating, you 412 * should provide this column to specify the rating style of your content. The data in the 413 * column must be one of the constant values specified in {@link android.media.Rating} 414 */ 415 public final static String SUGGEST_COLUMN_RATING_STYLE = "suggest_rating_style"; 416 417 /** 418 * Column name for suggestions cursor. <i>Optional.</i> If your content has a rating, you 419 * should provide this column to specify the rating score of your content. The data in the 420 * column is of float type. See {@link android.media.Rating} about valid rating scores for each 421 * rating style. 422 */ 423 public final static String SUGGEST_COLUMN_RATING_SCORE = "suggest_rating_score"; 424 425 /** 426 * Column name for suggestions cursor. <i>Optional.</i> If your content is video or audio and 427 * has a known production year, you should provide this column to specify the production year 428 * of your content. The data in the column is of integer type. 429 */ 430 public final static String SUGGEST_COLUMN_PRODUCTION_YEAR = "suggest_production_year"; 431 432 /** 433 * Column name for suggestions cursor. <i>Optional.</i> If your content is video or audio, you 434 * should provide this column to specify the duration of your content in milliseconds. The data 435 * in the column is of long type. 436 */ 437 public final static String SUGGEST_COLUMN_DURATION = "suggest_duration"; 438 439 /** 440 * Column name for suggestions cursor. <i>Optional.</i> This column is used to specify 441 * additional flags per item. Multiple flags can be specified. 442 * <p> 443 * Must be one of {@link #FLAG_QUERY_REFINEMENT} or 0 to indicate no flags. 444 * </p> 445 */ 446 public final static String SUGGEST_COLUMN_FLAGS = "suggest_flags"; 447 448 /** 449 * Column name for suggestions cursor. <i>Optional.</i> This column may be 450 * used to specify the time in {@link System#currentTimeMillis 451 * System.currentTImeMillis()} (wall time in UTC) when an item was last 452 * accessed within the results-providing application. If set, this may be 453 * used to show more-recently-used items first. 454 */ 455 public final static String SUGGEST_COLUMN_LAST_ACCESS_HINT = "suggest_last_access_hint"; 456 457 /** 458 * Column value for suggestion column {@link #SUGGEST_COLUMN_SHORTCUT_ID} when a suggestion 459 * should not be stored as a shortcut in global search. 460 */ 461 public final static String SUGGEST_NEVER_MAKE_SHORTCUT = "_-1"; 462 463 /** 464 * Query parameter added to suggestion queries to limit the number of suggestions returned. 465 * This limit is only advisory and suggestion providers may chose to ignore it. 466 */ 467 public final static String SUGGEST_PARAMETER_LIMIT = "limit"; 468 469 /** 470 * Intent action for starting the global search activity. 471 * The global search provider should handle this intent. 472 * 473 * Supported extra data keys: {@link #QUERY}, 474 * {@link #EXTRA_SELECT_QUERY}, 475 * {@link #APP_DATA}. 476 */ 477 public final static String INTENT_ACTION_GLOBAL_SEARCH 478 = "android.search.action.GLOBAL_SEARCH"; 479 480 /** 481 * Intent action for starting the global search settings activity. 482 * The global search provider should handle this intent. 483 */ 484 public final static String INTENT_ACTION_SEARCH_SETTINGS 485 = "android.search.action.SEARCH_SETTINGS"; 486 487 /** 488 * Intent action for starting a web search provider's settings activity. 489 * Web search providers should handle this intent if they have provider-specific 490 * settings to implement. 491 */ 492 public final static String INTENT_ACTION_WEB_SEARCH_SETTINGS 493 = "android.search.action.WEB_SEARCH_SETTINGS"; 494 495 /** 496 * Intent action broadcasted to inform that the searchables list or default have changed. 497 * Components should handle this intent if they cache any searchable data and wish to stay 498 * up to date on changes. 499 */ 500 public final static String INTENT_ACTION_SEARCHABLES_CHANGED 501 = "android.search.action.SEARCHABLES_CHANGED"; 502 503 /** 504 * Intent action to be broadcast to inform that the global search provider 505 * has changed. 506 */ 507 public final static String INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED 508 = "android.search.action.GLOBAL_SEARCH_ACTIVITY_CHANGED"; 509 510 /** 511 * Intent action broadcasted to inform that the search settings have changed in some way. 512 * Either searchables have been enabled or disabled, or a different web search provider 513 * has been chosen. 514 */ 515 public final static String INTENT_ACTION_SEARCH_SETTINGS_CHANGED 516 = "android.search.action.SETTINGS_CHANGED"; 517 518 /** 519 * This means that context is voice, and therefore the SearchDialog should 520 * continue showing the microphone until the user indicates that he/she does 521 * not want to re-speak (e.g. by typing). 522 * 523 * @hide 524 */ 525 public final static String CONTEXT_IS_VOICE = "android.search.CONTEXT_IS_VOICE"; 526 527 /** 528 * This means that the voice icon should not be shown at all, because the 529 * current search engine does not support voice search. 530 * @hide 531 */ 532 public final static String DISABLE_VOICE_SEARCH 533 = "android.search.DISABLE_VOICE_SEARCH"; 534 535 /** 536 * Reference to the shared system search service. 537 */ 538 private static ISearchManager mService; 539 540 private final Context mContext; 541 542 /** 543 * The package associated with this seach manager. 544 */ 545 private String mAssociatedPackage; 546 547 // package private since they are used by the inner class SearchManagerCallback 548 /* package */ final Handler mHandler; 549 /* package */ OnDismissListener mDismissListener = null; 550 /* package */ OnCancelListener mCancelListener = null; 551 552 private SearchDialog mSearchDialog; 553 554 /*package*/ SearchManager(Context context, Handler handler) { 555 mContext = context; 556 mHandler = handler; 557 mService = ISearchManager.Stub.asInterface( 558 ServiceManager.getService(Context.SEARCH_SERVICE)); 559 } 560 561 /** 562 * Launch search UI. 563 * 564 * <p>The search manager will open a search widget in an overlapping 565 * window, and the underlying activity may be obscured. The search 566 * entry state will remain in effect until one of the following events: 567 * <ul> 568 * <li>The user completes the search. In most cases this will launch 569 * a search intent.</li> 570 * <li>The user uses the back, home, or other keys to exit the search.</li> 571 * <li>The application calls the {@link #stopSearch} 572 * method, which will hide the search window and return focus to the 573 * activity from which it was launched.</li> 574 * 575 * <p>Most applications will <i>not</i> use this interface to invoke search. 576 * The primary method for invoking search is to call 577 * {@link android.app.Activity#onSearchRequested Activity.onSearchRequested()} or 578 * {@link android.app.Activity#startSearch Activity.startSearch()}. 579 * 580 * @param initialQuery A search string can be pre-entered here, but this 581 * is typically null or empty. 582 * @param selectInitialQuery If true, the intial query will be preselected, which means that 583 * any further typing will replace it. This is useful for cases where an entire pre-formed 584 * query is being inserted. If false, the selection point will be placed at the end of the 585 * inserted query. This is useful when the inserted query is text that the user entered, 586 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful 587 * if initialQuery is a non-empty string.</i> 588 * @param launchActivity The ComponentName of the activity that has launched this search. 589 * @param appSearchData An application can insert application-specific 590 * context here, in order to improve quality or specificity of its own 591 * searches. This data will be returned with SEARCH intent(s). Null if 592 * no extra data is required. 593 * @param globalSearch If false, this will only launch the search that has been specifically 594 * defined by the application (which is usually defined as a local search). If no default 595 * search is defined in the current application or activity, global search will be launched. 596 * If true, this will always launch a platform-global (e.g. web-based) search instead. 597 * 598 * @see android.app.Activity#onSearchRequested 599 * @see #stopSearch 600 */ 601 public void startSearch(String initialQuery, 602 boolean selectInitialQuery, 603 ComponentName launchActivity, 604 Bundle appSearchData, 605 boolean globalSearch) { 606 startSearch(initialQuery, selectInitialQuery, launchActivity, 607 appSearchData, globalSearch, null); 608 } 609 610 /** 611 * As {@link #startSearch(String, boolean, ComponentName, Bundle, boolean)} but including 612 * source bounds for the global search intent. 613 * 614 * @hide 615 */ 616 public void startSearch(String initialQuery, 617 boolean selectInitialQuery, 618 ComponentName launchActivity, 619 Bundle appSearchData, 620 boolean globalSearch, 621 Rect sourceBounds) { 622 if (globalSearch) { 623 startGlobalSearch(initialQuery, selectInitialQuery, appSearchData, sourceBounds); 624 return; 625 } 626 627 ensureSearchDialog(); 628 629 mSearchDialog.show(initialQuery, selectInitialQuery, launchActivity, appSearchData); 630 } 631 632 private void ensureSearchDialog() { 633 if (mSearchDialog == null) { 634 mSearchDialog = new SearchDialog(mContext, this); 635 mSearchDialog.setOnCancelListener(this); 636 mSearchDialog.setOnDismissListener(this); 637 } 638 } 639 640 /** 641 * Starts the global search activity. 642 */ 643 /* package */ void startGlobalSearch(String initialQuery, boolean selectInitialQuery, 644 Bundle appSearchData, Rect sourceBounds) { 645 ComponentName globalSearchActivity = getGlobalSearchActivity(); 646 if (globalSearchActivity == null) { 647 Log.w(TAG, "No global search activity found."); 648 return; 649 } 650 Intent intent = new Intent(INTENT_ACTION_GLOBAL_SEARCH); 651 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 652 intent.setComponent(globalSearchActivity); 653 // Make sure that we have a Bundle to put source in 654 if (appSearchData == null) { 655 appSearchData = new Bundle(); 656 } else { 657 appSearchData = new Bundle(appSearchData); 658 } 659 // Set source to package name of app that starts global search, if not set already. 660 if (!appSearchData.containsKey("source")) { 661 appSearchData.putString("source", mContext.getPackageName()); 662 } 663 intent.putExtra(APP_DATA, appSearchData); 664 if (!TextUtils.isEmpty(initialQuery)) { 665 intent.putExtra(QUERY, initialQuery); 666 } 667 if (selectInitialQuery) { 668 intent.putExtra(EXTRA_SELECT_QUERY, selectInitialQuery); 669 } 670 intent.setSourceBounds(sourceBounds); 671 try { 672 if (DBG) Log.d(TAG, "Starting global search: " + intent.toUri(0)); 673 mContext.startActivity(intent); 674 } catch (ActivityNotFoundException ex) { 675 Log.e(TAG, "Global search activity not found: " + globalSearchActivity); 676 } 677 } 678 679 /** 680 * Returns a list of installed apps that handle the global search 681 * intent. 682 * 683 * @hide 684 */ 685 public List<ResolveInfo> getGlobalSearchActivities() { 686 try { 687 return mService.getGlobalSearchActivities(); 688 } catch (RemoteException ex) { 689 Log.e(TAG, "getGlobalSearchActivities() failed: " + ex); 690 return null; 691 } 692 } 693 694 /** 695 * Gets the name of the global search activity. 696 */ 697 public ComponentName getGlobalSearchActivity() { 698 try { 699 return mService.getGlobalSearchActivity(); 700 } catch (RemoteException ex) { 701 Log.e(TAG, "getGlobalSearchActivity() failed: " + ex); 702 return null; 703 } 704 } 705 706 /** 707 * Gets the name of the web search activity. 708 * 709 * @return The name of the default activity for web searches. This activity 710 * can be used to get web search suggestions. Returns {@code null} if 711 * there is no default web search activity. 712 * 713 * @hide 714 */ 715 public ComponentName getWebSearchActivity() { 716 try { 717 return mService.getWebSearchActivity(); 718 } catch (RemoteException ex) { 719 Log.e(TAG, "getWebSearchActivity() failed: " + ex); 720 return null; 721 } 722 } 723 724 /** 725 * Similar to {@link #startSearch} but actually fires off the search query after invoking 726 * the search dialog. Made available for testing purposes. 727 * 728 * @param query The query to trigger. If empty, request will be ignored. 729 * @param launchActivity The ComponentName of the activity that has launched this search. 730 * @param appSearchData An application can insert application-specific 731 * context here, in order to improve quality or specificity of its own 732 * searches. This data will be returned with SEARCH intent(s). Null if 733 * no extra data is required. 734 * 735 * @see #startSearch 736 */ 737 public void triggerSearch(String query, 738 ComponentName launchActivity, 739 Bundle appSearchData) { 740 if (!mAssociatedPackage.equals(launchActivity.getPackageName())) { 741 throw new IllegalArgumentException("invoking app search on a different package " + 742 "not associated with this search manager"); 743 } 744 if (query == null || TextUtils.getTrimmedLength(query) == 0) { 745 Log.w(TAG, "triggerSearch called with empty query, ignoring."); 746 return; 747 } 748 startSearch(query, false, launchActivity, appSearchData, false); 749 mSearchDialog.launchQuerySearch(); 750 } 751 752 /** 753 * Terminate search UI. 754 * 755 * <p>Typically the user will terminate the search UI by launching a 756 * search or by canceling. This function allows the underlying application 757 * or activity to cancel the search prematurely (for any reason). 758 * 759 * <p>This function can be safely called at any time (even if no search is active.) 760 * 761 * @see #startSearch 762 */ 763 public void stopSearch() { 764 if (mSearchDialog != null) { 765 mSearchDialog.cancel(); 766 } 767 } 768 769 /** 770 * Determine if the Search UI is currently displayed. 771 * 772 * This is provided primarily for application test purposes. 773 * 774 * @return Returns true if the search UI is currently displayed. 775 * 776 * @hide 777 */ 778 public boolean isVisible() { 779 return mSearchDialog == null? false : mSearchDialog.isShowing(); 780 } 781 782 /** 783 * See {@link SearchManager#setOnDismissListener} for configuring your activity to monitor 784 * search UI state. 785 */ 786 public interface OnDismissListener { 787 /** 788 * This method will be called when the search UI is dismissed. To make use of it, you must 789 * implement this method in your activity, and call 790 * {@link SearchManager#setOnDismissListener} to register it. 791 */ 792 public void onDismiss(); 793 } 794 795 /** 796 * See {@link SearchManager#setOnCancelListener} for configuring your activity to monitor 797 * search UI state. 798 */ 799 public interface OnCancelListener { 800 /** 801 * This method will be called when the search UI is canceled. To make use if it, you must 802 * implement this method in your activity, and call 803 * {@link SearchManager#setOnCancelListener} to register it. 804 */ 805 public void onCancel(); 806 } 807 808 /** 809 * Set or clear the callback that will be invoked whenever the search UI is dismissed. 810 * 811 * @param listener The {@link OnDismissListener} to use, or null. 812 */ 813 public void setOnDismissListener(final OnDismissListener listener) { 814 mDismissListener = listener; 815 } 816 817 /** 818 * Set or clear the callback that will be invoked whenever the search UI is canceled. 819 * 820 * @param listener The {@link OnCancelListener} to use, or null. 821 */ 822 public void setOnCancelListener(OnCancelListener listener) { 823 mCancelListener = listener; 824 } 825 826 /** 827 * @deprecated This method is an obsolete internal implementation detail. Do not use. 828 */ 829 @Deprecated 830 public void onCancel(DialogInterface dialog) { 831 if (mCancelListener != null) { 832 mCancelListener.onCancel(); 833 } 834 } 835 836 /** 837 * @deprecated This method is an obsolete internal implementation detail. Do not use. 838 */ 839 @Deprecated 840 public void onDismiss(DialogInterface dialog) { 841 if (mDismissListener != null) { 842 mDismissListener.onDismiss(); 843 } 844 } 845 846 /** 847 * Gets information about a searchable activity. 848 * 849 * @param componentName The activity to get searchable information for. 850 * @return Searchable information, or <code>null</code> if the activity does not 851 * exist, or is not searchable. 852 */ 853 public SearchableInfo getSearchableInfo(ComponentName componentName) { 854 try { 855 return mService.getSearchableInfo(componentName); 856 } catch (RemoteException ex) { 857 Log.e(TAG, "getSearchableInfo() failed: " + ex); 858 return null; 859 } 860 } 861 862 /** 863 * Gets a cursor with search suggestions. 864 * 865 * @param searchable Information about how to get the suggestions. 866 * @param query The search text entered (so far). 867 * @return a cursor with suggestions, or <code>null</null> the suggestion query failed. 868 * 869 * @hide because SearchableInfo is not part of the API. 870 */ 871 public Cursor getSuggestions(SearchableInfo searchable, String query) { 872 return getSuggestions(searchable, query, -1); 873 } 874 875 /** 876 * Gets a cursor with search suggestions. 877 * 878 * @param searchable Information about how to get the suggestions. 879 * @param query The search text entered (so far). 880 * @param limit The query limit to pass to the suggestion provider. This is advisory, 881 * the returned cursor may contain more rows. Pass {@code -1} for no limit. 882 * @return a cursor with suggestions, or <code>null</null> the suggestion query failed. 883 * 884 * @hide because SearchableInfo is not part of the API. 885 */ 886 public Cursor getSuggestions(SearchableInfo searchable, String query, int limit) { 887 if (searchable == null) { 888 return null; 889 } 890 891 String authority = searchable.getSuggestAuthority(); 892 if (authority == null) { 893 return null; 894 } 895 896 Uri.Builder uriBuilder = new Uri.Builder() 897 .scheme(ContentResolver.SCHEME_CONTENT) 898 .authority(authority) 899 .query("") // TODO: Remove, workaround for a bug in Uri.writeToParcel() 900 .fragment(""); // TODO: Remove, workaround for a bug in Uri.writeToParcel() 901 902 // if content path provided, insert it now 903 final String contentPath = searchable.getSuggestPath(); 904 if (contentPath != null) { 905 uriBuilder.appendEncodedPath(contentPath); 906 } 907 908 // append standard suggestion query path 909 uriBuilder.appendPath(SearchManager.SUGGEST_URI_PATH_QUERY); 910 911 // get the query selection, may be null 912 String selection = searchable.getSuggestSelection(); 913 // inject query, either as selection args or inline 914 String[] selArgs = null; 915 if (selection != null) { // use selection if provided 916 selArgs = new String[] { query }; 917 } else { // no selection, use REST pattern 918 uriBuilder.appendPath(query); 919 } 920 921 if (limit > 0) { 922 uriBuilder.appendQueryParameter(SUGGEST_PARAMETER_LIMIT, String.valueOf(limit)); 923 } 924 925 Uri uri = uriBuilder.build(); 926 927 // finally, make the query 928 return mContext.getContentResolver().query(uri, null, selection, selArgs, null); 929 } 930 931 /** 932 * Returns a list of the searchable activities that can be included in global search. 933 * 934 * @return a list containing searchable information for all searchable activities 935 * that have the <code>android:includeInGlobalSearch</code> attribute set 936 * in their searchable meta-data. 937 */ 938 public List<SearchableInfo> getSearchablesInGlobalSearch() { 939 try { 940 return mService.getSearchablesInGlobalSearch(); 941 } catch (RemoteException e) { 942 Log.e(TAG, "getSearchablesInGlobalSearch() failed: " + e); 943 return null; 944 } 945 } 946 947 /** 948 * Gets an intent for launching installed assistant activity, or null if not available. 949 * @return The assist intent. 950 * 951 * @hide 952 */ 953 public Intent getAssistIntent(Context context, boolean inclContext) { 954 return getAssistIntent(context, inclContext, UserHandle.myUserId()); 955 } 956 957 /** 958 * Gets an intent for launching installed assistant activity, or null if not available. 959 * @return The assist intent. 960 * 961 * @hide 962 */ 963 public Intent getAssistIntent(Context context, boolean inclContext, int userHandle) { 964 try { 965 if (mService == null) { 966 return null; 967 } 968 ComponentName comp = mService.getAssistIntent(userHandle); 969 if (comp == null) { 970 return null; 971 } 972 Intent intent = new Intent(Intent.ACTION_ASSIST); 973 intent.setComponent(comp); 974 if (inclContext) { 975 IActivityManager am = ActivityManagerNative.getDefault(); 976 Bundle extras = am.getAssistContextExtras(0); 977 if (extras != null) { 978 intent.replaceExtras(extras); 979 } 980 } 981 return intent; 982 } catch (RemoteException re) { 983 Log.e(TAG, "getAssistIntent() failed: " + re); 984 return null; 985 } 986 } 987} 988