从不同的活动接收侦听器onResults()

时间:2016-04-29 21:03:20

标签: android android-activity listener android-custom-view actionresult

我正在使用SpeechRecognizer开发一款应用。我将在不同的活动中使用它以用于不同的用途。它有点脏,一直添加相同的代码到不同的类。所以我将自定义RecognitionListener移到了新课程。这样我就可以在我想要的时候初始化它。但是我找不到一种方法来接收我当前活动中使用它的监听器的结果(在这种情况下,识别语音的ArrayList可能值)。

我试图通过界面实现它,但我认为我是以错误的方式实现的。我的监听器代码是这样的:

public class SpeechRecognitionListener implements RecognitionListener
{
    private final String TAG = "SpeechRecognitionListener";
private Intent mSpeechRecognizerIntent;
private SpeechRecognizer mSpeechRecognizer;

public SpeechRecognitionListener(Intent speechRecognizerIntent, SpeechRecognizer speechRecognizer ) {
    mSpeechRecognizerIntent = speechRecognizerIntent;
    mSpeechRecognizer = speechRecognizer;
}

@Override
public void onBeginningOfSpeech()
{
    //Log.d(TAG, "onBeginingOfSpeech");
}

@Override
public void onBufferReceived(byte[] buffer)
{

}

@Override
public void onEndOfSpeech()
{
    //Log.d(TAG, "onEndOfSpeech");
}

@Override
public void onError(int error)
{
    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

    //Log.d(TAG, "error = " + error);
}

@Override
public void onEvent(int eventType, Bundle params)
{

}

@Override
public void onPartialResults(Bundle partialResults)
{

}

@Override
public void onReadyForSpeech(Bundle params)
{
    Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}

@Override
public void onResults(Bundle results)
{
    //I want to recieve this array in my main activity
    ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

}

@Override
public void onRmsChanged(float rmsdB)
{
}
}

我只想在当前活动中收到onResult()数组来使用它。希望有人能帮助我!非常感谢你!

1 个答案:

答案 0 :(得分:2)

首先尝试定义一个接口:

public interface RecognitionCallback
{
   abstract void onRecoginitionFinished(ArrayList<String> matches);
}

现在让您需要回调的活动实现此接口。例如:

public class MainActivity extends AppCompatActivity implements RecognitionCallback {

  ...

  public void onRecognitionFinished(ArrayList<String> matches)
  {
     //do your things with the data
  }

}

还添加SpeechRecognitionListener类的一些属性:

public class SpeechRecognitionListener implements RecognitionListener
{
    private final String TAG = "SpeechRecognitionListener";
    private Intent mSpeechRecognizerIntent;
    private SpeechRecognizer mSpeechRecognizer;
    private RecognitionCallback mCallback

    public SpeechRecognitionListener(Intent speechRecognizerIntent, SpeechRecognizer speechRecognizer, RecognitionCallback callback ) {
       mSpeechRecognizerIntent = speechRecognizerIntent;
       mSpeechRecognizer = speechRecognizer;
       mCallback = callback;

    ...

    public void onResults(Bundle results)
    {

       ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
       mCallback.onRecognitionFinished(matches);
    }
}    

最后在你需要被召回的活动中写下这个:

   SpeechRecognitionListener listener = new SpeechRecognitionLinstner(intent,recognizer,this);