Advertisement
daniilK

Netology 4.3 RecognizerIntent

Aug 7th, 2022
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.39 KB | None | 0 0
  1. // добавляем выше onCreate
  2.    private lateinit var launcher: ActivityResultLauncher<Intent>
  3.  
  4. // вызываем в onCreate
  5.    initResult()
  6.  
  7. // реализовываем
  8.  private fun initResult() {
  9.         launcher =
  10.             registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
  11.                 if (result.resultCode == RESULT_OK) {
  12.                     val res: ArrayList<String> =
  13.                         result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) as ArrayList<String>
  14.  
  15.                     val resultStr = Objects.requireNonNull(res)[0]
  16.                     requestInput.setText(resultStr)
  17.                     askWolfram(resultStr)
  18.                 }
  19.             }
  20.     }
  21.  
  22. // диалог
  23.   private fun showVoiceInputDialog() {
  24.         val language = "us-US"
  25.         val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
  26.             putExtra(
  27.                 RecognizerIntent.EXTRA_LANGUAGE_MODEL,
  28.                 language)
  29.             putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.request_hint))
  30.             putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
  31.         }
  32.         runCatching {
  33.             launcher.launch(intent)
  34.         }.onFailure { t ->
  35.             showSnackbar(t.message ?: getString(R.string.error_voice_recognition_unavailable))
  36.         }
  37.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement