Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
1000 / James Steele, Nelson To - The Android Developer’s Cookbook Building Applications with the Android SDK - 2010.pdf
3.58 Mб

Multiple Activities


Recipe: Launching an Activity for a Result Using Speech to Text

In this recipe, launching an activity for a result is demonstrated. It also demonstrates how to utilize speech to text functionality from Google’s RecognizerIntent and print the result to the screen. Here, the trigger event is a button press. It launches theRecognizerIntent activity, which does speech recognition on sound from the microphone and converts it into text.When finished, the text is passed back to the calling activity.

Upon return, the onActivityResult() function is first called with the returned data, and then theonResume() function is called to continue the activity as normal.The calling activity can have a problem and not return properly.Therefore, theresultCode should always be checked to ensureRESULT_OK before continuing to parse the returned data.

Note that in general any launched activity that returns data causes the same onActivityResult() function to be called.Therefore, a request code is customarily used to distinguish which activity is returning.When the launched activity finishes, it returns control to the calling activity and callsonActivityResult() with the same request code.

The steps for launching an activity for result are

1.Call startActivityForResult() with an intent, defining the launched activity and an identifying requestCode.

2.Override the onActivityResult() function to check on the status of the result, check for the expected requestCode, and parse the returned data.

The steps for using RecognizerIntent are

1.Declare an intent with action ACTION_RECOGNIZE_SPEECH.

2.Add any extras to the intent; at least EXTRA_LANGUAGE_MODEL is required.This can be set as either LANGUAGE_MODEL_FREE_FORM or LANGUAGE_MODEL_WEB_SEARCH.

3.The returned data bundle contains a list of strings with possible matches to the original text. Use data.getStringArrayListExtra to retrieve this data.This should be cast as an ArrayList for use later.

A TextView is used to display the returned text to the screen.The main activity is shown in Listing 2.14.

The additional supporting files needed are the main.xml andstrings.xml, which need to define a button and the TextView to hold the result.This is accomplished using Listing 2.10 and 2.12 in the “Launching Another Activity from an Event” recipe.The AndroidManifest needs to declare only the main activity, which is the same as the basic “Creating an Activity” recipe.The RecognizerIntent activity is native to the Android system and does not need to be declared explicitly to be utilized.

Download at www.wowebook.com

42Chapter 2 Application Basics: Activities and Intents

Listing 2.14 src/com/cookbook/launch_for_result/RecognizerIntent Example.java package com.cookbook.launch_for_result;

import java.util.ArrayList;

import android.app.Activity; import android.content.Intent; import android.os.Bundle;

import android.speech.RecognizerIntent; import android.view.View;

import android.widget.Button; import android.widget.TextView;

public class RecognizerIntentExample extends Activity { private static final int RECOGNIZER_EXAMPLE = 1001; private TextView tv;

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

tv = (TextView) findViewById(R.id.text_result);

//setup button listener

Button startButton = (Button) findViewById(R.id.trigger); startButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

// RecognizerIntent prompts for speech and returns text Intent intent =

new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say a word or phrase\nand it will show as text"); startActivityForResult(intent, RECOGNIZER_EXAMPLE);





protected void onActivityResult(int requestCode,

int resultCode, Intent data) { //use a switch statement for more than one request code check

if (requestCode==RECOGNIZER_EXAMPLE && resultCode==RESULT_OK) {

Download at www.wowebook.com

Multiple Activities


// returned data is a list of matches to the speech input ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

//display on screen tv.setText(result.toString());


super.onActivityResult(requestCode, resultCode, data);



Recipe: Implementing a List of Choices

A common situation in applications is to provide a user with a list of choices that can be selected by clicking them.This can be easily implemented utilizing ListActivity, a subclass ofActivity, and triggering an event based on what choice was made.

The steps for creating a list of choices are

1. Create a class that extends the ListActivity class instead of the Activity class:

public class ActivityExample extends ListActivity { //content here


2. Create a String array of labels for each choice:

static final String[] ACTIVITY_CHOICES = new String[] { "Action 1",

"Action 2", "Action 3"


3. Call setListAdapter()with the ArrayAdapterspecifying this list and a layout: setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, ACTIVITY_CHOICES)); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); getListView().setTextFilterEnabled(true);

4. Launch an OnItemClickListener to determine which choice was selected and act accordingly:

getListView().setOnItemClickListener(new OnItemClickListener()



public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

switch(arg2) {//extend switch to as many as needed case 0:

//code for action 1

Download at www.wowebook.com

44 Chapter 2 Application Basics: Activities and Intents


case 1:

//code for action 2


case 2:

//code for action 3


default: break;




This technique is utilized in the next recipe.

Recipe: Using Implicit Intents for Creating an Activity

Implicit intents do not specify an exact component to use. Instead, they specify the functionality required through a filter, and the Android system must determine the best component to utilize. An intent filter can be either an action, data, or a category.

The most commonly used intent filter is an action, and the most common action is ACTION_VIEW.This mode requires a uniform resource identifier (URI) to be specified and then displays the data to the user. It does the most reasonable action for the given URI. For example, the implicit intents in case 0, 1, and 2 in the following example have the same syntax but produce different results.

The steps for launching an activity using an implicit intent are

1.Declare the intent with the appropriate filter specified (ACTION_VIEW, ACTION_WEB_SEARCH, and so on).

2.Attach any extra information to the intent required to run the activity.

3.Pass this intent to startActivity().

This is shown for multiple intents in Listing 2.15.

Listing 2.15 src/com/cookbook/implicit_intents/ListActivityExample.java

package com.cookbook.implicit_intents;

import android.app.ListActivity; import android.app.SearchManager; import android.content.Intent; import android.net.Uri;

import android.os.Bundle; import android.view.View;

import android.widget.AdapterView; import android.widget.ArrayAdapter;

Download at www.wowebook.com

Multiple Activities


import android.widget.ListView;

import android.widget.AdapterView.OnItemClickListener;

public class ListActivityExample extends ListActivity { static final String[] ACTIVITY_CHOICES = new String[] {

"Open Website Example",

"Open Contacts",

"Open Phone Dialer Example",

"Search Google Example",

"Start Voice Command"


final String searchTerms = "superman";

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ACTIVITY_CHOICES));

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); getListView().setTextFilterEnabled(true); getListView().setOnItemClickListener(new OnItemClickListener()



public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

switch(arg2) {

case 0: //opens web browser and navigates to given website

startActivity(new Intent(Intent.ACTION_VIEW,



case 1: //opens contacts application to browse contacts

startActivity(new Intent(Intent.ACTION_VIEW,



case 2: //opens phone dialer and fills in the given number

startActivity(new Intent(Intent.ACTION_VIEW,



case 3: //search Google for the string

Intent intent= new Intent(Intent.ACTION_WEB_SEARCH );

intent.putExtra(SearchManager.QUERY, searchTerms);



case 4: //starts the voice command



Download at www.wowebook.com

Соседние файлы в папке 1000


Сервис бесплатной оценки стоимости работы

  1. Заполните заявку. Специалисты рассчитают стоимость вашей работы
  2. Расчет стоимости придет на почту и по СМС

Нажимая на кнопку, вы соглашаетесь с политикой конфиденциальности и на обработку персональных данных.

Номер вашей заявки

Прямо сейчас на почту придет автоматическое письмо-подтверждение с информацией о заявке.

Оформить еще одну заявку