如何获取设备的默认语音服务提供程序 - Android API 13

5

根据此页面,Android 13将删除SpeechService实现,包括RecognitionService。它还提到:

“应用程序应该使用设备的默认提供程序来获取SpeechService,而不是硬编码一个特定的应用程序。”

这是我在API 13以下使用的代码:

String GOOGLE_RECOGNITION_SERVICE_NAME =
        "com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService";

SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context,
            ComponentName.unflattenFromString(GOOGLE_RECOGNITION_SERVICE_NAME));

有什么办法可以获取设备上SpeechService的默认提供程序?
1个回答

1

我通过实现以下代码解决了这个问题:

public static String getAvailableVoiceRecognitionService(Activity activity)
{
    final List<ResolveInfo> services = activity.getPackageManager().queryIntentServices(
            new Intent(RecognitionService.SERVICE_INTERFACE), 0);

    String recognitionServiceName = null;

    for (final ResolveInfo info : services)
    {
        String packageName = info.serviceInfo.packageName;
        String serviceName = info.serviceInfo.name;

        String testRecognitionServiceName = packageName + "/" + serviceName;

        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        Intent serviceIntent = new Intent(RecognitionService.SERVICE_INTERFACE);

        ComponentName recognizerServiceComponent =
                ComponentName.unflattenFromString(testRecognitionServiceName);

        if (recognizerServiceComponent != null)
        {
            serviceIntent.setComponent(recognizerServiceComponent);
            try
            {
                boolean isServiceAvailableToBind = activity.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
                if (isServiceAvailableToBind) {
                    activity.unbindService(connection);
                    recognitionServiceName=testRecognitionServiceName;
                    break;
                }
            }
            catch (SecurityException e)
            {
                e.printStackTrace();
            }
        }
    }

    return recognitionServiceName;
}

然后,要启动SpeechRecognizer,您需要执行以下操作:
public void initSpeechRecognition(Activity activity)
{
   String recognitionServiceName = getAvailableVoiceRecognitionService(activity);
    if (recognitionServiceName==null)
        return;

    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(activity,
            ComponentName.unflattenFromString(recognitionServiceName));
 }



    

1
你能在Android 13中通过这种方式获取语言列表吗?我可以获取识别器“com.google.android.googlequicksearchbox”的语言列表,但似乎识别器变成了“com.google.android.tts”,无法通过RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS获取语言列表。 - Fisher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接