enviroCar / enviroCar-app

enviroCar Android Application
https://envirocar.org
GNU General Public License v3.0
87 stars 153 forks source link

Fix for speech recognition not working on activity change #987

Closed devAyushDubey closed 9 months ago

devAyushDubey commented 1 year ago

This potentially solves #986

I dug a little deep and found out that the problem here is multiple instantiations of AimyBox.

The AimyBox object is supposed to be instantiated only once during the lifecycle of the application (unless in special cases).

What is happening here is, the initAimyBoxViewModel() which is supposed to set the viewModel variable to the current AimyBoxAssistantViewModel, ends up creating a new instance of AimyBox every time it is called.

https://user-images.githubusercontent.com/33064931/229193760-7d558567-a227-48fd-ac8a-318adcf0e2f5.mp4

The new instance of AimyBox creates new workers and connections to Google TTS and SpeechRecognizer, which causes closes the RezendvousChannel set up by the one of the SpeechRecognizers, as a result two workers running two instances of SpeechRecognizer at the same time, hence no input is detected.

- Two instances of SpeechRecognizer:

Screenshot (1023)

- New instance of AimyBox created on entering CarSelection

Screenshot (1025)

It is because once we instantiate AimyBox, we are not storing its instance statically for future reference as AimyBox works on coroutine scope, it does not get destroyed by activity changes.

Potential Solution:

I implemented a simple logic to store the instance of the AimyBox class to its companion object so that it can be referenced further anywhere down the line.

In BaseApplication.java

public Aimybox getAimybox() {
      BaseAimybox.Companion.setCurrentAimybox(new BaseAimybox(this, mBus, metadataHandler).getAimybox());
      return BaseAimybox.Companion.getCurrentAimybox();
}

In BaseAimyBox.kt

fun setCurrentAimybox(aimybox: Aimybox) {
            currentAimybox = aimybox;
}

fun getCurrentAimybox() : Aimybox? {
            return currentAimybox;
}

A review to this would be great, @cdhiraj40

https://user-images.githubusercontent.com/33064931/229200903-6bb810be-faab-4c8f-8186-d6e61713de4a.mp4

devAyushDubey commented 9 months ago

Solved in #992