0

I'm working with the voice recognition API with the code that is already provided within the API examples the feature that I want in the same activity example is:

A) that it works even when my phone is not used that is when the screen is locked. B) If the googleAPI doesn't find the word it shows a dialog saying cancel/speak again then code selects speak again by itself ,how to go about.

Here's the code:

package com.wwwww.and;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Sample code that invokes the speech recognition intent API.
 */
public class VoiceRecognition extends Activity implements OnClickListener {

    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

    private ListView mList;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Inflate our UI from its XML layout description.
        setContentView(R.layout.voice_recognition);

        // Get display items for later interaction
        Button speakButton = (Button) findViewById(R.id.btn_speak);

        mList = (ListView) findViewById(R.id.list);

        // Check to see if a recognition activity is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() != 0) {
            speakButton.setOnClickListener(this);
        } else {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");
        }
        startVoiceRecognitionActivity();
    }

    /**
     * Handle the click on the start recognition button.
     */
    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak) {
            //startVoiceRecognitionActivity();
        }
    }

    /**
     * Fire an intent to start the speech recognition activity.
     */
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, " VoiceRecognition Service");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }

    /**
     * Handle the results from the recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
            // Fill the list view with the strings the recognizer thought it could have heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    matches));
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Naaz
  • 273
  • 2
  • 6
  • 21

1 Answers1

1
A) that it works even when my phone is not used that is when the screen is locked.  

You need to implement the speech recognition in a service.

B) If the googleAPI doesn't find the word it shows a dialog saying cancel/speak again then code selects speak again by itself ,how to go about.    

Change your onActivityResult to the one below

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) 
    {
      if (resultCode == RESULT_OK)
      {
        // Fill the list view with the strings the recognizer thought it could have heard
        ArrayList<String> matches;
        if (data != null)
        {
              matches = data.getStringArrayListExtra(
                RecognizerIntent.EXTRA_RESULTS);
        }

        if (data == null || matches.size() == 0)
        {
             startVoiceRecognitionActivity();
        }
        else
        {
             mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                matches));
        }
     }
     else
     {
         startVoiceRecognitionActivity();
     }
   }

    super.onActivityResult(requestCode, resultCode, data);
}
Hoan Nguyen
  • 18,033
  • 3
  • 50
  • 54
  • Thanks! will try and get back to you whether I'm ok or not – Naaz Mar 22 '13 at 09:44
  • I edited the answer. Just move the declaration of matches outside the if. – Hoan Nguyen Mar 22 '13 at 15:24
  • ok the error was resolved but it still shows speak again and is not restarting the function of taking input automatically – Naaz Mar 22 '13 at 20:13
  • I tested and as it is as your comment above. onActivityResult is not called until you pressed the cancel button. You can get around this by setting up a timer and if onActivityResult is not called by certain amount of time, then kill the recognizer activity and start again. It is not perfect though, the user may see cancel and speak again for a few second. If you want I will edit the code. – Hoan Nguyen Mar 22 '13 at 22:39
  • You better off implement a service, then there would not be any problem. – Hoan Nguyen Mar 23 '13 at 02:17
  • The coder here provides the ability to cancel the process if NO MATCH FOUND happens ,I searched further and folks told me to utilise the SpeechRecognizer to get control over UI – Naaz Mar 23 '13 at 05:24
  • That is what I meant by telling you to implement a service. If you have problem let me know. My app work very well. I would like to know how using your code if NO MATCH FOUND, he can cancel it. The onActivityResult would not be called until a user press cancel or there is a match. That is why I would implement a timer and shut down the google recognizer UI after say 5 seconds and then call startVoiceRecognitionActivity() again. – Hoan Nguyen Mar 23 '13 at 05:45
  • So implementing the same code in a service would provide me the ability to cancel it? here is the code see for yourself if its happening or not >> https://code.google.com/p/adk-moto/source/browse/src/com/jmoyer/adk_moto/ADKMoto.java – Naaz Mar 23 '13 at 09:29
  • The code in the link you refer above extends activity and not service. However that should work fine, the code for service is pretty much the same except there is no view. When implement this way, there is no Google UI, so there is no such thing as cancel. By the way, on Jelly Bean my code above works. – Hoan Nguyen Mar 23 '13 at 17:39
  • Thanks! Hoan Nguyen what I do is to check on your code and use it in a Service and then we see the outcome. – Naaz Mar 24 '13 at 17:27
  • You cannot use my code in the service, it won't work in a service. The code in the link above would work. – Hoan Nguyen Mar 24 '13 at 17:29
  • I have faced a lot of problem with that code in the link, its too much mixed up with other functions – Naaz Mar 26 '13 at 08:12
  • First do you know how to create a service? – Hoan Nguyen Mar 26 '13 at 08:13
  • It's OK, in onCreate you initialize the recognizer engine, and then you have to create a Listener class. That all you have to do. Just look up the the document at http://developer.android.com/reference/android/speech/SpeechRecognizer.html – Hoan Nguyen Mar 26 '13 at 08:35
  • You do not need wake lock in a service, remove the wakelock code – Hoan Nguyen Mar 26 '13 at 08:46
  • Still it doesn't work as it should ,So what I have done is to define a service register it in manifest and from the beginning write my own service – Naaz Mar 26 '13 at 08:48
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26917/discussion-between-hoan-nguyen-and-user1898249) – Hoan Nguyen Mar 26 '13 at 08:49
  • The much a lot I have researched ,I have been told that I can't use the service without the UI , The UI has to be there, whereas I wanted to do like give a BUTTON in a ACtivity which says START SPEECH RECOGNITION and after clicking on it the SPEECH REC SERVICE starts and then users can minimise the app or even lock the phone screen as it normally happens but still the speech recognition works!!!!! Is it possible? – Naaz Mar 28 '13 at 15:41
  • No you can use service without the UI, any service you create would run on the UI thread by default. My app always run does not matter what, I can leave it overnight and in the morning say something and it will respond. The code in the pastebin above look OK in general. I guess it is just bug here and there but I do not have time to look at it. – Hoan Nguyen Mar 28 '13 at 15:58
  • thats great! I so what all changes you consider I make in that pastebin code ,Just remove the wakelock. Also I have seen another of your Service code here >> http://stackoverflow.com/questions/14940657/android-speech-recognition-as-a-service-on-android-4-1-4-2 should I take this? – Naaz Mar 28 '13 at 17:23
  • Yes you can use that and onResult implement what ever you want. I forgot all about that post. – Hoan Nguyen Mar 28 '13 at 17:26
  • You should vote that up if you find it usefuf, if people vote my useful post, then I am reminded of my post. – Hoan Nguyen Mar 28 '13 at 18:21
  • I have been able to get your code into My own service now I'm just facing 2 problems first is 1) setStreamMute eclipse is showing me only one solution that is "add cast to mAudioManager" should I go by it? second 2) in the if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) I'm not getting the JELLY_BEAN there I just have till FROYO however I have loaded SDK manager till latest jelly bean my own phone is ICS , What to do about this? here's the code >> http://pastebin.com/pFZhRaFx – Naaz Mar 28 '13 at 18:26
  • Put this one as a class member protected AudioManager mAudioManager; – Hoan Nguyen Mar 28 '13 at 18:28
  • That code is for phone that has JB. You should leave it just as is so that a phone with JB will work properly. – Hoan Nguyen Mar 28 '13 at 18:30
  • Go to that side and discuss there – Hoan Nguyen Mar 28 '13 at 18:52
  • You need minSDKVersion 8 and set maxSDKVersion 17 in your manifest and let discuss at the service post. – Hoan Nguyen Mar 28 '13 at 18:59
  • "Did min max SDK in manifest" the problem isn't solved still its not showing anything bigger than FROYO – Naaz Mar 28 '13 at 19:17
  • right click your project ---> properties ---> Android and check 17. right click your project ---> Android tools ---> Fix Project ... – Hoan Nguyen Mar 28 '13 at 19:20
  • Thanks! Hoan No Errors now! What Next? I should do? I mean how to get text values of spoken words – Naaz Mar 28 '13 at 19:39
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/27126/discussion-between-hoan-nguyen-and-user1898249) – Hoan Nguyen Mar 28 '13 at 19:43
  • My service starts great and I know its enters OnCreate(); but after that I speak and My Service doesn't seem to enter the onResults(); in onResults(); I'm doing a LOG print and also a Toast – Naaz Mar 29 '13 at 08:12
  • Have entered the Log.d prints at other places as well as you had in your programme but nothing appears? just the service oncreate() calls up – Naaz Mar 29 '13 at 08:15
  • You have to call startListening somewhere, but I am busy right now tomorrow we can talk – Hoan Nguyen Mar 29 '13 at 08:18
  • Called mSpeechRecognizer.startListening(mSpeechRecognizerIntent); at the OnCreate(); of the service still things aren't picking up! – Naaz Mar 29 '13 at 10:55
  • Okay take care of you and your work, Please get back to me whenever possible, Thanks! – Naaz Mar 29 '13 at 11:00
  • Did you get the time to review,HOAN? – Naaz Mar 31 '13 at 11:15
  • I look at the link and you did not do anything but paste my code there. Change Object mAudioManager to AudioManager mAudioManager. Try call startListening in onCreate see if it does anything. – Hoan Nguyen Mar 31 '13 at 20:56
  • no, I have already changed the code to AudioManager mAudioManager and also had onCreate() startListening ,I didnt update code on the LINK sorry for that – Naaz Apr 01 '13 at 04:12
  • How did you start the service? – Hoan Nguyen Apr 01 '13 at 04:13
  • You have to wait a little bit before you talk when startListening in onCreate. – Hoan Nguyen Apr 01 '13 at 04:15
  • here's the code >> http://pastebin.com/VW39Afx4 , I start the service with a startService(new Intent(this, VoiceService.class)); in my home activity that starts when the app starts – Naaz Apr 01 '13 at 04:16
  • just put Log.d("VoiceService", results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)); and see if you get anything on logcat. – Hoan Nguyen Apr 01 '13 at 04:19
  • I implemented that LOG in onResults() however the method isn't taking it! and eclipse says "The method d(String, String) in the type Log is not applicable for the arguments (String, ArrayList)" – Naaz Apr 01 '13 at 04:21
  • Log.d("VoiceService", results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION).toString()); – Hoan Nguyen Apr 01 '13 at 04:23
  • Not getting anything in onResults() , I'm using mSpeechRecognizer.startListening(mSpeechRecognizerIntent); in onCreate() of the service to start the speechrec fine? – Naaz Apr 01 '13 at 04:27
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/27299/discussion-between-user1898249-and-hoan-nguyen) – Naaz Apr 01 '13 at 04:28
  • The code is working now ,But it just works for once! ,Im now getting everywhere from onerror to start listening and its working but only once ,The problem was that you weren't starting the recognitionListener by making a new instance, whatever? here is the code >> http://pastebin.com/VW39Afx4 – Naaz Apr 02 '13 at 07:21
  • I am pretty busy today, after you finish handle onResults you have to call startListening again. – Hoan Nguyen Apr 02 '13 at 07:28
  • I did the same but it keeps on running pretty fast andI cant see the results – Naaz Apr 02 '13 at 07:33
  • solved all! just one thing more My service stops when the phone screen locks, want it to run and take inputs even then! – Naaz Apr 02 '13 at 08:08
  • Ok that Done! too, Thanks for all of your great help! – Naaz Apr 02 '13 at 08:56