SpeechRecognizerpublic class SpeechRecognizer extends Object This class provides access to the speech recognition service. This service allows access to the
speech recognizer. Do not instantiate this class directly, instead, call
{@link SpeechRecognizer#createSpeechRecognizer(Context)}. This class's methods must be
invoked only from the main application thread.
The implementation of this API is likely to stream audio to remote servers to perform speech
recognition. As such this API is not intended to be used for continuous recognition, which would
consume a significant amount of battery and bandwidth.
Please note that the application must have {@link android.Manifest.permission#RECORD_AUDIO}
permission to use this class. |
Fields Summary |
---|
private static final boolean | DBGDEBUG value to enable verbose debug prints | private static final String | TAGLog messages identifier | public static final String | RESULTS_RECOGNITIONKey used to retrieve an {@code ArrayList} from the {@link Bundle} passed to the
{@link RecognitionListener#onResults(Bundle)} and
{@link RecognitionListener#onPartialResults(Bundle)} methods. These strings are the possible
recognition results, where the first element is the most likely candidate. | public static final String | CONFIDENCE_SCORESKey used to retrieve a float array from the {@link Bundle} passed to the
{@link RecognitionListener#onResults(Bundle)} and
{@link RecognitionListener#onPartialResults(Bundle)} methods. The array should be
the same size as the ArrayList provided in {@link #RESULTS_RECOGNITION}, and should contain
values ranging from 0.0 to 1.0, or -1 to represent an unavailable confidence score.
Confidence values close to 1.0 indicate high confidence (the speech recognizer is confident
that the recognition result is correct), while values close to 0.0 indicate low confidence.
This value is optional and might not be provided. | public static final int | ERROR_NETWORK_TIMEOUTNetwork operation timed out. | public static final int | ERROR_NETWORKOther network related errors. | public static final int | ERROR_AUDIOAudio recording error. | public static final int | ERROR_SERVERServer sends error status. | public static final int | ERROR_CLIENTOther client side errors. | public static final int | ERROR_SPEECH_TIMEOUTNo speech input | public static final int | ERROR_NO_MATCHNo recognition result matched. | public static final int | ERROR_RECOGNIZER_BUSYRecognitionService busy. | public static final int | ERROR_INSUFFICIENT_PERMISSIONSInsufficient permissions | private static final int | MSG_STARTaction codes | private static final int | MSG_STOP | private static final int | MSG_CANCEL | private static final int | MSG_CHANGE_LISTENER | private IRecognitionService | mServiceThe actual RecognitionService endpoint | private Connection | mConnectionThe connection to the actual service | private final android.content.Context | mContextContext with which the manager was created | private final android.content.ComponentName | mServiceComponentComponent to direct service intent to | private android.os.Handler | mHandlerHandler that will execute the main tasks | private final Queue | mPendingTasksTemporary queue, saving the messages until the connection will be established, afterwards,
only mHandler will receive the messages | private final InternalListener | mListenerThe Listener that will receive all the callbacks |
Constructors Summary |
---|
private SpeechRecognizer(android.content.Context context, android.content.ComponentName serviceComponent)The right way to create a {@code SpeechRecognizer} is by using
{@link #createSpeechRecognizer} static factory method
mContext = context;
mServiceComponent = serviceComponent;
|
Methods Summary |
---|
public void | cancel()Cancels the speech recognition. Please note that
{@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise
no notifications will be received.
checkIsCalledFromMainThread();
putMessage(Message.obtain(mHandler, MSG_CANCEL));
| private static void | checkIsCalledFromMainThread()
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new RuntimeException(
"SpeechRecognizer should be used only from the application's main thread");
}
| private boolean | checkOpenConnection()
if (mService != null) {
return true;
}
mListener.onError(ERROR_CLIENT);
Log.e(TAG, "not connected to the recognition service");
return false;
| public static android.speech.SpeechRecognizer | createSpeechRecognizer(android.content.Context context)Factory method to create a new {@code SpeechRecognizer}. Please note that
{@link #setRecognitionListener(RecognitionListener)} should be called before dispatching any
command to the created {@code SpeechRecognizer}, otherwise no notifications will be
received.
return createSpeechRecognizer(context, null);
| public static android.speech.SpeechRecognizer | createSpeechRecognizer(android.content.Context context, android.content.ComponentName serviceComponent)Factory method to create a new {@code SpeechRecognizer}. Please note that
{@link #setRecognitionListener(RecognitionListener)} should be called before dispatching any
command to the created {@code SpeechRecognizer}, otherwise no notifications will be
received.
Use this version of the method to specify a specific service to direct this
{@link SpeechRecognizer} to. Normally you would not use this; use
{@link #createSpeechRecognizer(Context)} instead to use the system default recognition
service.
if (context == null) {
throw new IllegalArgumentException("Context cannot be null)");
}
checkIsCalledFromMainThread();
return new SpeechRecognizer(context, serviceComponent);
| public void | destroy()Destroys the {@code SpeechRecognizer} object.
if (mService != null) {
try {
mService.cancel(mListener);
} catch (final RemoteException e) {
// Not important
}
}
if (mConnection != null) {
mContext.unbindService(mConnection);
}
mPendingTasks.clear();
mService = null;
mConnection = null;
mListener.mInternalListener = null;
| private void | handleCancelMessage()sends the actual message to the service
if (!checkOpenConnection()) {
return;
}
try {
mService.cancel(mListener);
if (DBG) Log.d(TAG, "service cancel command succeded");
} catch (final RemoteException e) {
Log.e(TAG, "cancel() failed", e);
mListener.onError(ERROR_CLIENT);
}
| private void | handleChangeListener(RecognitionListener listener)changes the listener
if (DBG) Log.d(TAG, "handleChangeListener, listener=" + listener);
mListener.mInternalListener = listener;
| private void | handleStartListening(android.content.Intent recognizerIntent)sends the actual message to the service
if (!checkOpenConnection()) {
return;
}
try {
mService.startListening(recognizerIntent, mListener);
if (DBG) Log.d(TAG, "service start listening command succeded");
} catch (final RemoteException e) {
Log.e(TAG, "startListening() failed", e);
mListener.onError(ERROR_CLIENT);
}
| private void | handleStopMessage()sends the actual message to the service
if (!checkOpenConnection()) {
return;
}
try {
mService.stopListening(mListener);
if (DBG) Log.d(TAG, "service stop listening command succeded");
} catch (final RemoteException e) {
Log.e(TAG, "stopListening() failed", e);
mListener.onError(ERROR_CLIENT);
}
| public static boolean | isRecognitionAvailable(android.content.Context context)Checks whether a speech recognition service is available on the system. If this method
returns {@code false}, {@link SpeechRecognizer#createSpeechRecognizer(Context)} will
fail.
final List<ResolveInfo> list = context.getPackageManager().queryIntentServices(
new Intent(RecognitionService.SERVICE_INTERFACE), 0);
return list != null && list.size() != 0;
| private void | putMessage(android.os.Message msg)
if (mService == null) {
mPendingTasks.offer(msg);
} else {
mHandler.sendMessage(msg);
}
| public void | setRecognitionListener(RecognitionListener listener)Sets the listener that will receive all the callbacks. The previous unfinished commands will
be executed with the old listener, while any following command will be executed with the new
listener.
checkIsCalledFromMainThread();
putMessage(Message.obtain(mHandler, MSG_CHANGE_LISTENER, listener));
| public void | startListening(android.content.Intent recognizerIntent)Starts listening for speech. Please note that
{@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise
no notifications will be received.
if (recognizerIntent == null) {
throw new IllegalArgumentException("intent must not be null");
}
checkIsCalledFromMainThread();
if (mConnection == null) { // first time connection
mConnection = new Connection();
Intent serviceIntent = new Intent(RecognitionService.SERVICE_INTERFACE);
if (mServiceComponent == null) {
String serviceComponent = Settings.Secure.getString(mContext.getContentResolver(),
Settings.Secure.VOICE_RECOGNITION_SERVICE);
if (TextUtils.isEmpty(serviceComponent)) {
Log.e(TAG, "no selected voice recognition service");
mListener.onError(ERROR_CLIENT);
return;
}
serviceIntent.setComponent(ComponentName.unflattenFromString(serviceComponent));
} else {
serviceIntent.setComponent(mServiceComponent);
}
if (!mContext.bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE)) {
Log.e(TAG, "bind to recognition service failed");
mConnection = null;
mService = null;
mListener.onError(ERROR_CLIENT);
return;
}
}
putMessage(Message.obtain(mHandler, MSG_START, recognizerIntent));
| public void | stopListening()Stops listening for speech. Speech captured so far will be recognized as if the user had
stopped speaking at this point. Note that in the default case, this does not need to be
called, as the speech endpointer will automatically stop the recognizer listening when it
determines speech has completed. However, you can manipulate endpointer parameters directly
using the intent extras defined in {@link RecognizerIntent}, in which case you may sometimes
want to manually call this method to stop listening sooner. Please note that
{@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise
no notifications will be received.
checkIsCalledFromMainThread();
putMessage(Message.obtain(mHandler, MSG_STOP));
|
|