First, you can use the following code to test whether your machine has the speech recognition function:
[Java]
PackageManager pm = getPackageManager ();
List <ResolveInfo> activities = pm. queryIntentActivities (
New Intent (RecognizerIntent. ACTION_RECOGNIZE_SPEECH), 0 );
If (activities. size ()! = 0 ){
/* Activity exists */
Toast. makeText (AndroidVoiceActivity. this, "Activity exists", Toast. LENGTH_LONG). show ();
} Else {
/* Activity Not Found will throw ActivityNotFoundException if it is Not determined */
Toast. makeText (AndroidVoiceActivity. this, "Activity does not exist", Toast. LENGTH_LONG). show ();
}
Simple Activity:
[Java]
Package com. relin. voice;
Import java. util. ArrayList;
Import java. util. List;
Import android. app. Activity;
Import android. content. Intent;
Import android. content. pm. PackageManager;
Import android. content. pm. ResolveInfo;
Import android. OS. Bundle;
Import android. speech. RecognizerIntent;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. Toast;
Public class AndroidVoiceActivity extends Activity {
/** Called when the activity is first created .*/
Private static final int VOICE_RECOGNITION_REQUEST_CODE = 1;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Button button = (Button) findViewById (R. id. button1 );
Button. setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
Try {
Intent intent = new Intent (RecognizerIntent. ACTION_RECOGNIZE_SPEECH );
Intent. putExtra (RecognizerIntent. EXTRA_LANGUAGE_MODEL, RecognizerIntent. LANGUAGE_MODEL_FREE_FORM );
Intent. putExtra (RecognizerIntent. EXTRA_PROMPT, "Start voice ");
StartActivityForResult (intent, VOICE_RECOGNITION_REQUEST_CODE );
} Catch (Exception e ){
// TODO: handle exception
Toast. makeText (AndroidVoiceActivity. this, "ActivityNotFoundException", Toast. LENGTH_LONG). show ();
}
}
});
}
@ Override
Protected void onActivityResult (int requestCode, int resultCode, Intent data ){
// TODO Auto-generated method stub
If (requestCode = VOICE_RECOGNITION_REQUEST_CODE & resultCode = RESULT_ OK ){
ArrayList <String> result = data. getStringArrayListExtra (RecognizerIntent. EXTRA_RESULTS );
String resultString = "";
For (int I = 0; I <result. size (); I ++ ){
ResultString + = result. get (I );
}
Toast. makeText (this, resultString, Toast. LENGTH_LONG). show ();
}
Super. onActivityResult (requestCode, resultCode, data );
}
}