everyone! I am developing an application for voice recognition, and the application is able to recognize the speech right now! However, I need to run this voice recognition code at the background of the app, it has to listen to the commands all the time. For my app, I wrote Handler().postDelayed function, it calculates the time when the user lands a new activity and it starts listening by delaying for 5 seconds. My problem is that it just listens 2-3 seconds, and it is not able to recognize and listen again. How can I run voice recognition at the background of the app when the app is running?
speechRecognizer1.setRecognitionListener(new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle bundle) {
ArrayList<String> matches1 =bundle.getStringArrayList(speechRecognizer1.RESULTS_RECOGNITION);
String string="";
if(matches1!=null) {
string = matches1.get(0);
textView3.setText(string);
Speak();
}
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
});
mTTS1 = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
int result= mTTS1.setLanguage(Locale.ENGLISH);
if(result== TextToSpeech.LANG_MISSING_DATA || result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS","Language Not Supported");
}
}
}
});
new Handler().postDelayed(new Runnable(){
public void run(){
speechRecognizer1.startListening(intentRecognizer1);
}
}, 5000);
Ok for this you need an android component called Service we have three types of services in android :
for your case you can use a foreground service. to decide what is better and how to implement it or deciding between a thread and a service I recommend reading this document : https://developer.android.com/guide/components/services