【问题标题】:Android - SpeechRecognizer in Serivce - Error 9 but I have all permissionsAndroid - Serivce 中的 SpeechRecognizer - 错误 9 但我拥有所有权限
【发布时间】:2021-04-15 14:16:42
【问题描述】:

我在Service中使用了SpeechRecognizer,它只在我第一次调用speechRecognizer.startListening()时工作,然后它出现代码9的错误(权限不足)。

如果在 Activity 中,它工作得很好。

我的应用中的权限:

<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

识别器意图

private val intent by lazy {
        Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).run {
            putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
            putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
            putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.applicationContext.packageName)
        }
    }

请帮帮我。

提前致谢。

【问题讨论】:

标签: android android-service speech-recognition


【解决方案1】:

您可以使用SpeechRecognizer 代替 RecognizerIntent。它在服务中运行良好。你可以像这样在OnStartCommand 中初始化它:

    @Override
public int onStartCommand(Intent intent,int flags,int startId) {

    Toast.makeText(this,"start Service.",Toast.LENGTH_SHORT).show();

    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
    speechRecognizer.setRecognitionListener(this);

    Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    voice.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
            .getPackage().getName());
    voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    voice.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);

    speechRecognizer.startListening(voice);

    return START_REDELIVER_INTENT;
}

更多详情:https://developer.android.com/reference/android/speech/SpeechRecognizer

【讨论】:

  • 谢谢。但这种方式与我的方式相同。代码 9 仍然出错。
【解决方案2】:

我对这个 Service 主题还很陌生,但是 SpeechRecognizer 的官方文档是否指出你不在 MainThread 上时不能使用它?

只能从主应用程序调用此类的方法 线程。

https://developer.android.com/reference/android/speech/SpeechRecognizer

这可能很愚蠢,但您是否在运行时要求用户提供这些权限?

我应该将此作为评论而不是答案,但 Answer 的编辑器工作得更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2013-09-15
    • 1970-01-01
    • 2021-04-10
    相关资源
    最近更新 更多