FileDocCategorySizeDatePackage
SpeechRecognizer.javaAPI DocAndroid 5.1 API20084Thu Mar 12 22:22:10 GMT 2015android.speech

SpeechRecognizer

public 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
DBG
DEBUG value to enable verbose debug prints
private static final String
TAG
Log messages identifier
public static final String
RESULTS_RECOGNITION
Key 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_SCORES
Key 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_TIMEOUT
Network operation timed out.
public static final int
ERROR_NETWORK
Other network related errors.
public static final int
ERROR_AUDIO
Audio recording error.
public static final int
ERROR_SERVER
Server sends error status.
public static final int
ERROR_CLIENT
Other client side errors.
public static final int
ERROR_SPEECH_TIMEOUT
No speech input
public static final int
ERROR_NO_MATCH
No recognition result matched.
public static final int
ERROR_RECOGNIZER_BUSY
RecognitionService busy.
public static final int
ERROR_INSUFFICIENT_PERMISSIONS
Insufficient permissions
private static final int
MSG_START
action codes
private static final int
MSG_STOP
private static final int
MSG_CANCEL
private static final int
MSG_CHANGE_LISTENER
private IRecognitionService
mService
The actual RecognitionService endpoint
private Connection
mConnection
The connection to the actual service
private final android.content.Context
mContext
Context with which the manager was created
private final android.content.ComponentName
mServiceComponent
Component to direct service intent to
private android.os.Handler
mHandler
Handler that will execute the main tasks
private final Queue
mPendingTasks
Temporary queue, saving the messages until the connection will be established, afterwards, only mHandler will receive the messages
private final InternalListener
mListener
The 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 voidcancel()
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 voidcheckIsCalledFromMainThread()

        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new RuntimeException(
                    "SpeechRecognizer should be used only from the application's main thread");
        }
    
private booleancheckOpenConnection()

        if (mService != null) {
            return true;
        }
        mListener.onError(ERROR_CLIENT);
        Log.e(TAG, "not connected to the recognition service");
        return false;
    
public static android.speech.SpeechRecognizercreateSpeechRecognizer(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.

param
context in which to create {@code SpeechRecognizer}
return
a new {@code SpeechRecognizer}

        return createSpeechRecognizer(context, null);
    
public static android.speech.SpeechRecognizercreateSpeechRecognizer(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.

param
context in which to create {@code SpeechRecognizer}
param
serviceComponent the {@link ComponentName} of a specific service to direct this {@code SpeechRecognizer} to
return
a new {@code SpeechRecognizer}

        if (context == null) {
            throw new IllegalArgumentException("Context cannot be null)");
        }
        checkIsCalledFromMainThread();
        return new SpeechRecognizer(context, serviceComponent);
    
public voiddestroy()
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 voidhandleCancelMessage()
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 voidhandleChangeListener(RecognitionListener listener)
changes the listener

        if (DBG) Log.d(TAG, "handleChangeListener, listener=" + listener);
        mListener.mInternalListener = listener;
    
private voidhandleStartListening(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 voidhandleStopMessage()
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 booleanisRecognitionAvailable(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.

param
context with which {@code SpeechRecognizer} will be created
return
{@code true} if recognition is available, {@code false} otherwise

        final List<ResolveInfo> list = context.getPackageManager().queryIntentServices(
                new Intent(RecognitionService.SERVICE_INTERFACE), 0);
        return list != null && list.size() != 0;
    
private voidputMessage(android.os.Message msg)

        if (mService == null) {
            mPendingTasks.offer(msg);
        } else {
            mHandler.sendMessage(msg);
        }
    
public voidsetRecognitionListener(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.

param
listener listener that will receive all the callbacks from the created {@link SpeechRecognizer}, this must not be null.

        checkIsCalledFromMainThread();
        putMessage(Message.obtain(mHandler, MSG_CHANGE_LISTENER, listener));
    
public voidstartListening(android.content.Intent recognizerIntent)
Starts listening for speech. Please note that {@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise no notifications will be received.

param
recognizerIntent contains parameters for the recognition to be performed. The intent may also contain optional extras, see {@link RecognizerIntent}. If these values are not set explicitly, default values will be used by the recognizer.

        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 voidstopListening()
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));