Search >

Using the Android Search Dialog

When you want to provide search in your application, the last thing you should have to worry about is where to put your search box. By using the Android search framework, your application will reveal a custom search dialog whenever the user requests it. At the press of a dedicated search key or an API call from your application, the search dialog will appear at the top of the screen and will automatically show your application icon. An example is shown in the screenshot below.

This guide will teach you how to set up your application to provide search in a custom search dialog. In doing so, you will provide a standardized search experience and be able to add features like voice search and search suggestions.

The Basics

The Android search framework will manage the search dialog on your behalf; you never need to draw it or worry about where it is, and your current Activity will not be interrupted. The SearchManager is the component that does this work for you (hereafter, referred to as "the Search Manager"). It manages the life of the Android search dialog and will send your application the search query when executed by the user.

When the user executes a search, the Search Manager will use a specially-formed Intent to pass the search query to the Activity that you've declared to handle searches. Essentially, all you need is an Activity that receives this Intent, performs the search, and presents the results. Specifically, what you need is the following:

A searchable configuration
This is an XML file that configures the search dialog and includes settings for features such as the hint text shown in text box and settings voice search and search suggestion.
A searchable Activity
This is the Activity that receives the search query then searches your data and displays the search results.
A mechanism by which the user can invoke search
By default, the device search key (if available) will invoke the search dialog once you've configured a searchable Activity. However, you should always provide another means by which the user can invoke a search, such as with a search button in the Options Menu or elsewhere in the Activity UI, because not all devices provide a dedicated search key.

Creating a Searchable Configuration

The searchable configuration is an XML file that defines several settings for the Android search dialog in your application. This file is traditionally named searchable.xml and must be saved in the res/xml/ project directory.

The file must consist of the <searchable> element as the root node and specify one or more attributes that configure your search dialog. For example:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_label" >
</searchable>

This is the minimum configuration required in order to provide the search dialog. The android:label attribute is the only required attribute and points to a string resource, which should normally be the same as the application. (Although it's required, this label isn't actually shown to the user until you enable suggestions for Quick Search Box.)

There are several other attributes accepted by the <searchable> element. Most of which apply only when configuring features such as search suggestions and voice search. However, we recommend that you always include the android:hint attribute, which specifies a string resource for the text to display in the search dialog's text box before the user enters their query—it provides important clues to the user about what they can search.

Tip: For consistency among other Android applications, you should format the string for android:hint as "Search <content-or-product>". For example, "Search songs and artists" or "Search YouTube".

Next, you'll hook this configuration into your application.

Creating a Searchable Activity

When the user executes a search from the search dialog, the Search Manager will send your searchable Activity the search query with the ACTION_SEARCH Intent. Your searchable Activity will then search your data and present the results.

Declaring a searchable Activity

If you don't have one already, create an Activity that will be used to perform searches, then declare it to accept the ACTION_SEARCH Intent and apply the searchable configuration. To do so, you need to add an <intent-filter> element and a <meta-data> element to the appropriate <activity> element in your manifest file. For example:

<application ... >
    <activity android:name=".MySearchableActivity" >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <meta-data android:name="android.app.searchable"
                   android:resource="@xml/searchable"/>
    </activity>
    ...
</application>

The android:name attribute in the <meta-data> element must be defined with "android.app.searchable" and the android:resource attribute value must be a reference to the searchable configuration file saved in res/xml (in this example, it refers to the res/xml/searchable.xml file).

If you're wondering why the <intent-filter> does not include a <category> with the DEFAULT value, it's because the Intent that is delivered to this Activity when a search is executed will explicitly define this Activity as the component for the Intent (which the Search Manager knows from the searcahble meta-data declared for the Activity).

Be aware that the search dialog will not be available from within every Activity of your application, by default. Rather, the search dialog will be presented to users only when they invoke search from a searchable context of your application. A searchable context is any Activity for which you have declared searchable meta-data in the manifest file. For example, the searchable Activity itself (declared in the manifest snippet above) is a searchable context because it contains searchable meta-data that defines the searchable configuration. Any other Activity in your application is not a searchable context, by default, and thus, will not reveal the search dialog. You probably do want the search dialog to be available from every Activity in your application, so this can be easily fixed.

If you want all of your activities to provide the search dialog, add another <meta-data> element inside the <application> element. Use this element to declare the existing searchable Activity as the default searchable Activity. For example:

<application ... >
    <activity android:name=".MySearchableActivity" >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <meta-data android:name="android.app.searchable"
                   android:resource="@xml/searchable"/>
    </activity>
    <activity android:name=".AnotherActivity" ... >
    </activity>
    <!-- this one declares the searchable Activity for the whole app -->
    <meta-data android:name="android.app.default_searchable"
               android:value=".MySearchableActivity" />
    ...
</application>

The <meta-data> element with the android:name attribute value of "android.app.default_searchable" specifies a default searchable Activity for the context in which it is placed (which, in this case, is the entire application). The searchable Activity to use is specified with the android:value attribute. All other activities in the application, such as AnotherActivity, are now considered a searchable context and can invoke the search dialog. When a search is executed, MySearchableActivity will be launched to handle the search query.

Notice that this allows you to control which activities provide search at a more granular level. To specify only an individual Activity as a searchable context, simply place the <meta-data> with the "android.app.default_searchable" name inside the respective <activity> element (rather than inside the <application>). And, while it is uncommon, you can even create more than one searchable Activity and provide each one in different contexts of your application, either by declaring a different searchable Activity in each <activity> element, or declaring a default searchable Activity for the entire application and then overriding it with a different <meta-data> element inside certain activities.

Performing a search

Once your Activity is declared searchable, performing the actual search involves three steps: receiving the query, searching your data, and presenting the results.

Traditionally, your search results should be presented in a ListView (assuming that our results are text-based), so you may want your searchable Activity to extend ListActivity, which provides easy access to ListView APIs. (See the List View Tutorial for a simple ListActivity sample.)

Receiving the query

When a search is executed from the search dialog, your searchable Activity will be opened with the ACTION_SEARCH Intent, which carries the search query in the QUERY extra. All you need to do is check for this Intent and extract the string. For example, here's how you can get the query when your Activity launches:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

    Intent intent = getIntent();

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
      String query = intent.getStringExtra(SearchManager.QUERY);
      doMySearch(query);
    }
}

The QUERY string is always included with the ACTION_SEARCH Intent. In this example, the query is retrieved and passed to a local doMySearch() method where the actual search operation is done.

Searching your data

The process of storing and searching your data is a process that's unique to your application. There are many ways that you might do this and discussing all options is beyond the scope of this document. This guide will not teach you how to store your data and search it; this is something you must carefully consider in terms of your needs and your data. However, here are some tips you may be able to apply:

  • If your data is stored in a SQLite database on the device, performing a full-text search (using FTS3, rather than a LIKE query) can provide a more robust search across text data and can produce results many, many times faster. See sqlite.org for information about FTS3 and the SQLiteDatabase class for information about SQLite on Android. Also look at the Searchable Dictionary sample application to see a complete SQLite implementation that performs searches with FTS3.
  • If your data is stored online, then the perceived search performance may be inhibited by the user's data connection. You may want to display a spinning progress wheel until your search returns. See android.net for a reference of network APIs and Creating a Progress Dialog to see how you can display a progress wheel.

Regardless of where your data lives and how you search it, we recommend that you return search results to your searchable Activity with an Adapter. This way, you can easily present all the search results in a ListView. If your data comes from a SQLite database query, then you can easily apply your results to a ListView using a CursorAdapter. If your data comes in some other type of format, then you can create an extension of the BaseAdapter.

Presenting the results

Presenting your search results is mostly a UI detail and not something covered by the search framework APIs. However, a simple solution is to create your searchable Activity to extend ListActivity and then call setListAdapter(ListAdapter), passing it an Adapter that is bound to your data. This will automatically project all the results into the Activity ListView.

For more help presenting your results, see the ListActivity documentation.

Also see the Searchable Dictionary sample application for an a complete demonstration of how to search an SQLite database and use an Adapter to provide resuls in a ListView.

Invoking the Search Dialog

Once you have a searchable Activity in place, invoking the search dialog so the user can submit a query is easy. Many Android devices provide a dedicated search key and when it is pressed while the user is within a searchable context of your application, the search dialog will be revealed. However, you should never assume that a search key is available on the user's device and should always provide a search button in your UI that will invoke search.

To invoke search from your Activity, simply call onSearchRequested().

For example, you should provide a menu item in your Options Menu or a button in your UI to invoke search with this method. For your convenience, this search_icons.zip file includes icons for medium and high density screens, which you can use for your menu item or button (low density screens will automatically scale-down the hdpi image by one half).

You can also enable "type-to-search" functionality in your Activity by calling setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL). When this is enabled and the user begins typing on the keyboard, search will automatically be invoked and the keystrokes will be inserted in the search dialog. Be sure to enable this mode during your Activity onCreate() method.

The impact of the search dialog on your Activity life-cycle

The search dialog behaves like a Dialog that floats at the top of the screen. It does not cause any change in the Activity stack, so no life-cycle methods (such as onPause()) will be called. All that happens is your Activity loses input focus as it is given to the search dialog.

If you want to be notified when search is invoked, simply override the onSearchRequested() method. When this is called, you can do any work you may want to do when your Activity looses input focus (such as pause animations). But unless you are Passing Search Context Data (discussed above), you should always call the super class implementation. For example:

@Override
public boolean onSearchRequested() {
    pauseSomeStuff();
    return super.onSearchRequested();
}

If the user cancels search by pressing the device Back key, the Activity in which search was invoked will re-gain input focus. You can register to be notified when the search dialog is closed with setOnDismissListener(SearchManager.OnDismissListener) and/or setOnCancelListener(SearchManager.OnCancelListener). You should normally only need to register the OnDismissListener, because this is called every time that the search dialog is closed. The OnCancelListener only pertains to events in which the user explicitly left the search dialog, so it is not called when a search is executed (in which case, the search dialog naturally disappears).

If the current Activity is not the searchable Activity, then the normal Activity life-cycle events will be triggered once the user executes a search (the current Activity will receive onPause() and so forth, as described in Application Fundamentals). If, however, the current Activity is the searchable Activity, then one of two things will happen:

  • By default, the searchable Activity will receive the ACTION_SEARCH Intent with a call to onCreate() and a new instance of the Activity will be brought to the top of the stack. You'll now have two instances of your searchable Activity in the Activity stack (so pressing the Back key will go back to the previous instance of the searchable Activity, rather than exiting the searchable Activity).
  • On the other hand, if the Activity has set android:launchMode to "singleTop" then the searchable Activity will receive the ACTION_SEARCH Intent with a call to onNewIntent(Intent), passing the new ACTION_SEARCH Intent here. For example, here's how you might want to handle this case:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        handleIntent(getIntent());
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
    }
    
    private void handleIntent(Intent intent) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
          String query = intent.getStringExtra(SearchManager.QUERY);
          doMySearch(query);
        }
    }
    

    Compared to the example code in the section about Performing a Search, all the code to handle the search Intent has been moved outside the onCreate() method so it can also be executed from onNewIntent(). It's important to note that when onNewIntent(Intent) is called, the Activity has not been restarted, so the getIntent() method will still return the Intent that was first received with onCreate(). This is why setIntent(Intent) is called inside onNewIntent(Intent) (just in case you call getIntent() at a later time).

This second scenario is normally ideal, because the chances are good that once a search is completed, the user will perform additional searches and it's a bad experience if your application piles multiple instances of the searchable Activity on the stack. So we recommend that you set your searchable Activity to "singleTop" launch mode in the application manifest. For example:

<activity android:name=".MySearchableActivity"
              android:launchMode="singleTop" >
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
                      android:resource="@xml/searchable"/>
  </activity>

Passing Search Context Data

In order to refine your search criteria, you may want to provide some additional data to your searchable Activity when a search is executed. For instance, when you search your data, you may want to filter results based on more than just the search query text. In a simple case, you could just make your refinements inside the searchable Activity, for every search made. If, however, your search criteria may vary from one searchable context to another, then you can pass whatever data is necessary to refine your search in the APP_DATA Bundle, which is included in the ACTION_SEARCH Intent.

To pass this kind of data to your searchable Activity, you need to override onSearchRequested() method for the Activity in which search will be invoked. For example:

@Override
public boolean onSearchRequested() {
     Bundle appData = new Bundle();
     appData.putBoolean(MySearchableActivity.JARGON, true);
     startSearch(null, false, appData, false);
     return true;
 }

Returning "true" indicates that you have successfully handled this callback event. Then in your searchable Activity, you can extract this data from the APP_DATA Bundle to refine the search. For example:

 Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);
 if (appData != null) {
     boolean jargon = appData.getBoolean(MySearchableActivity.JARGON);
 }

Note: You should never call the startSearch() method from outside the onSearchRequested() callback method. When you want to invoke the search dialog, always call onSearchRequested() so that custom implementations (such as the addition of appData, in the above example) can be accounted for.

Adding Voice Search

You can easily add voice search functionality to your search dialog by adding the android:voiceSearchMode attribute to your searchable configuration. This will add a voice search button in the search dialog that, when clicked, will launch a voice prompt. When the user has finished speaking, the transcribed search query will be sent to your searchable Activity.

To enable voice search for your activity, add the android:voiceSearchMode attribute to your searchable configuration. For example:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/search_label"
    android:hint="@string/search_hint"
    android:voiceSearchMode="showVoiceSearchButton|launchRecognizer" >
</searchable>

The value showVoiceSearchButton is required to enable voice search, while the second value, launchRecognizer, specifies that the voice search button should launch a recognizer that returns the transcribed text to the searchable Activity. This is how most applications should declare this attribute.

There are some additional attributes you can provide to specify the voice search behavior, such as the language to be expected and the maximum number of results to return. See the Searchable Configuration for more information about the available attributes.

Note: Carefully consider whether voice search is appropriate for your application. All searches performed with the voice search button will be immediately sent to your searchable Activity without a chance for the user to review the transcribed query. Be sure to sufficiently test the voice recognition and ensure that it understands the types of queries that the user will submit inside your application.

↑ Go to top

← Back to Search