Why is UtteranceProgressListener not an interface?

2020-02-12 07:49发布

问题:

I'm playing around with Android's TTS features and the TextToSpeech class has this method to set a listener which gets notified once the TextToSpeech has finished playing:

public int setOnUtteranceCompletedListener(TextToSpeech.OnUtteranceCompletedListener listener)

But the OnUtteranceCompletedListener is defined as public abstract class. As my MainActivity already extends Activity, it can't extend OnUtteranceCompletedListener as well. I could use the older method with a OnUtteranceCompletedListener, but this is deprecated:

public int setOnUtteranceCompletedListener (TextToSpeech.OnUtteranceCompletedListener listener)`

Why is OnUtteranceCompletedListener not defined as public static interface? I'm thinking to write my own UtteranceProgressListenerImpl, which will then just call the MainActivitys onDone method. Is this the proper way or is there a better/cleaner alternative?

private class UtteranceProgressListenerImpl extends UtteranceProgressListener {

    private MainActivity mainActivity;

    UtteranceProgressListenerImpl(MainActivity mA) {
        mainActivity = mA;
    }

    @Override
    public void onDone(String utteranceId) {
        mainActivity.onDone(utteranceId);
    }

    @Override
    public void onError(String utteranceId) { /* empty */ }

    @Override
    public void onStart(String utteranceId) { /* empty */ }


}

回答1:

I don't know I think it should be an interface as well. I use this code to get around it. It is available here as well.

Also, vote for this bug I submitted a while ago.

public void setTts(TextToSpeech tts)
    {
        this.tts = tts;
        if (Build.VERSION.SDK_INT >= 15)
        {
            tts.setOnUtteranceProgressListener(new UtteranceProgressListener()
            {
                @Override
                public void onDone(String utteranceId)
                {
                    onDoneSpeaking(utteranceId);
                }

                @Override
                public void onError(String utteranceId)
                {
                }

                @Override
                public void onStart(String utteranceId)
                {
                }
            });
        }
        else
        {
            Log.d(TAG, "set utternace completed listener");
            tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener()
            {
                @Override
                public void onUtteranceCompleted(String utteranceId)
                {
                    onDoneSpeaking(utteranceId);
                }
            });
        }
    }