当屏幕方向改变时,维持片段中的文本到语音对话

时间:2014-03-03 08:51:13

标签: android android-fragments text-to-speech screen-orientation

我正在将基于活动的应用转换为片段以适应平板电脑。 我有一些文本到语音API的活动,如果屏幕旋转,它会继续说话,因为它们会保留在清单文件中。

为此,我将旧活动拆分为三个类:父活动,UI片段和带setRetainInstance(true)的无头片段,包括文本转语音功能。所有这些都通过活动通过接口链接(我已经看到这是正确的方法)。我没有在清单中选择“方向”。

但现在,我的问题是当屏幕旋转时,语音会关闭。调试过程,TTS在所有娱乐过程中发言,但当活动恢复时,TTS会丢失并停止。

感谢您的帮助。

活动:

     public class ParentActivity extends Main_Activity implements
            Fragment_ListaCorta.Callbacks, Fragment_UI.Callbacks,
            Fragment_Retain.Callbacks {

        public static final String ORIGEN = ParentActivity .class
                .getSimpleName();

    Fragment_Retain fragmentRetain;
    Fragment_UI fragmentUI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(Activity_Principal.preferencias.getTema(this));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment);

        super.context = this;

        if (findViewById(R.id.framelayout_contenedor_detalle) != null) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            fragmentUI = new Fragment_UI();
            fragmentRetain = (Fragment_Retain) fm
                    .findFragmentByTag(Fragment_Retain.NOMBRE_FRAGMENTO);
            if (fragmentRetain == null) {
                fragmentRetain = new Fragment_Retain();
                ft.add(fragmentRetain,
                        Fragment_Retain.NOMBRE_FRAGMENTO);
            }
            ft.replace(R.id.framelayout_contenedor_detalle, fragmentUI,
                    Fragment_UI.NOMBRE_FRAGMENTO);
            ft.commit();

        } else {
            FragmentManager fm = getSupportFragmentManager();

            FragmentTransaction ft = fm.beginTransaction();
            fragmentUI= new Fragment_UI();
            fragmentRetain = (Fragment_Retain) fm
                    .findFragmentByTag(Fragment_Retain.NOMBRE_FRAGMENTO);
            if (fragmentRetain == null) {
                fragmentRetain = new Fragment_Retain();
                ft.add(fragmentRetain ,
                        Fragment_Retain.NOMBRE_FRAGMENTO);
            }
            ft.replace(R.id.framelayout_contenedor_detalle1, fragmentUI,
                    Fragment_UI.NOMBRE_FRAGMENTO);
            ft.commit();
        }
    }

    @Override
    public void onEntradaSelecionada(String id) {
        int idInt = Integer.valueOf(id);
        opcionMenuActiv(idInt);
    }

    @Override
    public void onUIBotonPulsado(int posicion) {
        fragmentRetain.onClick();
    }

    @Override
    public void onRetainCambiaUltimoPlay(String ultimoPlay,
            String utteranceId) {
        fragmentUI.onCambioParrafo(ultimoPlay, utteranceId);
    }

    @Override
    public void onTtsOk(boolean oK) {
        if (oK) {
            runOnUiThread(new Runnable() {
                public void run() {
                    fragmentUI.buttonTextToSpeech
                            .setVisibility(View.VISIBLE);
                }
            });
        } else {
            runOnUiThread(new Runnable() {
                public void run() {
                    fragmentUI.buttonTextToSpeech
                            .setVisibility(View.GONE);
                }
            });
        }
    }
}

用户界面片段

 public class Fragment_UI extends Main_Fragment implements
            OnClickListener {

        public static ImageButton buttonTextToSpeech;
    TextView textView01, textView02, textView03, textView04, textView05,
            textView06, textView07, textView08, textView09, textView10,
            textView11, textView12, textView13, textView14, textView15,
            textView16, textView17, textView18, textView19, textView20,
            textView21;
    String tts01, tts02, tts03, tts04, tts05, tts06, tts07, tts08, tts09,
            tts10, tts11, tts12, tts13, tts14, tts15, tts16, tts17, tts18,
            tts19, tts20, tts21;

    private static final String[] ESTROFA = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17",
            "18", "19", "20" };

    private int colorDestacado;
    private int colorAnterior;

    (...)
protected int textView21Color;

    public static final String NOMBRE_FRAGMENTO = Fragment_UI.class
            .getSimpleName();
    public static final int PLAY = 1;
    public static final int PAUSE = 2;
    private static int mPosicion = PLAY;
    public boolean ttsOk = false;


    private Callbacks mCallbacks = CallbacksVacios;


    public interface Callbacks {

        public void onUIBotonPulsado(int posicion);
    }


    private static Callbacks CallbacksVacios = new Callbacks() {
        @Override
        public void onUIBotonPulsado(int posicion) {
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof Callbacks)) {
            throw new IllegalStateException(
                    "Error: La actividad debe implementar el callback del fragmento");
        }
        mCallbacks = (Callbacks) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = CallbacksVacios;
    }


    public Fragment_UI() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment,
                container, false);

        TypedArray a = getActivity().getTheme().obtainStyledAttributes(
                new int[] { R.attr.colorTts });
        colorDestacado = getResources().getColor(a.getResourceId(0, 0));
        a.recycle();

        buttonTextToSpeech = (ImageButton) rootView
                .findViewById(R.id.buttonTextToSpeech);
        if (Activity_Principal.preferencias.getTTSCheck()) {
            if (Activity_Principal.preferencias.getTTSok()) {
                buttonTextToSpeech.setVisibility(View.VISIBLE);
                buttonTextToSpeech.setOnClickListener(this);
            }
        }

        textView01 = (TextView) rootView.findViewById(R.id.textView01);
        ...
        textView20 = (TextView) rootView.findViewById(R.id.textView20);
        textView21 = (TextView) rootView.findViewById(R.id.textView21);

        tts01 = textView01.getText().toString();
        tts02 = textView02.getText().toString();
        tts03 = textView03.getText().toString();
        tts04 = textView04.getText().toString();
        tts05 = textView05.getText().toString();
        tts06 = textView06.getText().toString();
        tts07 = textView07.getText().toString();
        tts08 = textView08.getText().toString();
        tts09 = textView09.getText().toString();
        tts10 = textView10.getText().toString();
        tts11 = textView11.getText().toString();
        tts12 = textView12.getText().toString();
        tts13 = textView13.getText().toString();
        tts14 = textView14.getText().toString();
        tts15 = textView15.getText().toString();
        tts16 = textView16.getText().toString();
        tts17 = textView17.getText().toString();
        tts18 = textView18.getText().toString();
        tts19 = textView19.getText().toString();
        tts20 = textView20.getText().toString();
        tts21 = textView21.getText().toString();

        if (tts01 == "")
            textView01.setVisibility(View.GONE);
        if (tts02 == "")
            textView02.setVisibility(View.GONE);
        if (tts03 == "")
            textView03.setVisibility(View.GONE);
        if (tts04 == "")
            textView04.setVisibility(View.GONE);
        if (tts05 == "")
            textView05.setVisibility(View.GONE);
        if (tts06 == "")
            textView06.setVisibility(View.GONE);
        if (tts07 == "")
            textView07.setVisibility(View.GONE);
        if (tts08 == "")
            textView08.setVisibility(View.GONE);
        if (tts09 == "")
            textView09.setVisibility(View.GONE);
        if (tts10 == "")
            textView10.setVisibility(View.GONE);
        if (tts11 == "")
            textView11.setVisibility(View.GONE);
        if (tts12 == "")
            textView12.setVisibility(View.GONE);
        if (tts13 == "")
            textView13.setVisibility(View.GONE);
        if (tts14 == "")
            textView14.setVisibility(View.GONE);
        if (tts15 == "")
            textView15.setVisibility(View.GONE);
        if (tts16 == "")
            textView16.setVisibility(View.GONE);
        if (tts17 == "")
            textView17.setVisibility(View.GONE);
        if (tts18 == "")
            textView18.setVisibility(View.GONE);
        if (tts19 == "")
            textView19.setVisibility(View.GONE);
        if (tts20 == "")
            textView20.setVisibility(View.GONE);
        if (tts21 == "")
            textView21.setVisibility(View.GONE);

        return rootView;
    }

    public void onClick(View view) {

        switch (view.getId()) {

        case R.id.buttonTextToSpeech:

            mCallbacks.onUIBotonPulsado(R.id.buttonTextToSpeech);
            if (mPosicion == PLAY) {
                buttonTextToSpeech.setImageResource(R.drawable.button_pause);
                mPosicion = PAUSE;
            } else {
                buttonTextToSpeech.setImageResource(R.drawable.button_play);
                mPosicion = PLAY;
            }
            break;
        }
    }

    public void onCambioParrafo(String ultimoPlay, String utteranceId) {
        if (ultimoPlay.equals("")) {
            if (utteranceId.equals(ESTROFA[0])) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        colorAnterior = textView01.getCurrentTextColor();
                        textView01.setTextColor(colorDestacado);
                        textView01Color = textView01.getCurrentTextColor();
                    }
                });
            }//...

            } else if (utteranceId.equals(ESTROFA[21])) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        textView21.setTextColor(colorAnterior);
                        textView21Color = 0;

                        buttonTextToSpeech
                                .setImageResource(R.drawable.button_play);
                        mPosicion = PLAY;
                    }
                });
            }
        }
    }
}

使用TTS保留片段

    public class Fragment_Retain extends Main_Fragment implements
            TextToSpeech.OnInitListener {

        private static String tts01, tts02, tts03, tts04, tts05, tts06, tts07, tts08, tts09,
                tts10, tts11, tts12, tts13, tts14, tts15, tts16, tts17, tts18,
                tts19, tts20, tts21;

    private static String ultimoPlay = "";

    private static final String[] ESTROFA = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17",
            "18", "19", "20" };

    public static final String NOMBRE_FRAGMENTO = Fragment_Retain.class
            .getSimpleName();


    private Callbacks mCallbacks = CallbacksVacios;


    public interface Callbacks {

        public void onRetainCambiaUltimoPlay(String ultimoPlay,
                String utteranceId);

        public void onTtsOk(boolean oK);
    }


    private static Callbacks CallbacksVacios = new Callbacks() {
        @Override
        public void onRetainCambiaUltimoPlay(String ultimoPlay,
                String utteranceId) {
        }

        @Override
        public void onTtsOk(boolean oK) {
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        Log.i("Retain", "onAttach");

        if (!(activity instanceof Callbacks)) {
            throw new IllegalStateException(
                    "Error: La actividad debe implementar el callback del fragmento");
        }
        mCallbacks = (Callbacks) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();

        mCallbacks = CallbacksVacios;
    }


    public Fragment_Retain() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("Retain", "onCreate");

        setRetainInstance(true);

        // Inicio proceso TTS
        if (!Activity_Principal.preferencias.getTTSNoMostrar()
                && !Activity_Principal.preferencias.getTTSCheck()) {
            android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
            DialogoAdvertenciaTTS dialogo = new DialogoAdvertenciaTTS();
            dialogo.show(fragmentManager, "tagPersonalizado");
        }

        // Control proceso TTS
        if (Activity_Principal.preferencias.getTTSCheck()) {
            if (Activity_Principal.preferencias.getTTSok()) {
                tts = new TextToSpeech(getActivity(), this);
                if (tts.isSpeaking()) {
                    buttonTextToSpeech.setImageResource(R.drawable.button_pause);
                }
            } else {
                Intent checkTTSIntent = new Intent();
                checkTTSIntent
                        .setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
                startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
            }
        }

        tts01 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario01));
        tts02 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario02));
        tts03 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario03));
        tts04 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario04));
        tts05 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario05));
        tts06 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario06));
        tts07 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario07));
        tts08 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario08));
        tts09 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario09));
        tts10 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario10));
        tts11 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario11));
        tts12 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario12));
        tts13 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario13));
        tts14 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario14));
        tts15 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario15));
        tts16 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario16));
        tts17 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario17));
        tts18 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario18));
        tts19 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario19));
        tts20 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario20));
        tts21 = Utiles.depurarTextoTTS(getResources().getString(
                R.string.sagrario21));
    }

    public void onClick() {

        Log.i("Retain", "onClick");
        if (tts.isSpeaking()) {
            ultimoPlay = params.get(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID);
            tts.stop();
        } else {

            if (ultimoPlay.equals("") || ultimoPlay.equals(ESTROFA[0])) {
                speakOut(tts01, TextToSpeech.QUEUE_FLUSH, ESTROFA[0]);
                mCallbacks.onFragmentRetainCambiaUltimoPlay("", ESTROFA[0]);
            } else if (ultimoPlay.equals(ESTROFA[1])) {
                speakOut(tts02, TextToSpeech.QUEUE_FLUSH, ESTROFA[1]);
                mCallbacks.onFragmentRetainCambiaUltimoPlay("", ESTROFA[1]);
            } else if (ultimoPlay.equals(ESTROFA[2])) {
                speakOut(tts03, TextToSpeech.QUEUE_FLUSH, ESTROFA[2]);
                mCallbacks.onFragmentRetainCambiaUltimoPlay("", ESTROFA[2]);
            }....

            ....} else if (ultimoPlay.equals(ESTROFA[20])) {
                speakOut(tts21, TextToSpeech.QUEUE_FLUSH, ESTROFA[20]);
                mCallbacks.onFragmentRetainCambiaUltimoPlay("", ESTROFA[20]);
            }
            ultimoPlay = "";
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("Retain", "onActivityResult");
        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                tts = new TextToSpeech(getActivity(), this);
            } else { // missing data, install it Intent
                Intent installIntent = new Intent();
                installIntent
                        .setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

    public void onInit(int status) {

        Log.i("Retain", "onInit");
        if (status == TextToSpeech.SUCCESS) {

            Locale loc = new Locale(langPagina);
            int result = tts.isLanguageAvailable(loc);
            if (result == TextToSpeech.LANG_AVAILABLE) {
                tts.setLanguage(loc);
                Activity_Principal.preferencias.setTTSok(true);
                mCallbacks.onTtsOk(true);
                hablarTexto();
            } else {
                Log.e("TTS", "This Language is not supported");

                mCallbacks.onTtsOk(false);
                Activity_Principal.preferencias.setTTSok(false);
                String mensaje = getActivity().getString(
                        R.string.ttsIdiomaNoSoportadoToast);
                Toast toast = Toast.makeText(getActivity()
                        .getApplicationContext(), mensaje, Toast.LENGTH_LONG);
                toast.show();
            }

        } else {
            Log.e("TTS", "Initilization Failed!");
            Activity_Principal.preferencias.setTTSok(false);
        }
    }

    @SuppressLint("NewApi")
    private void hablarTexto() {

        Log.i("Retain", "hablarTexto");
        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);
                }

            });
        }
    }

    private void onDoneSpeaking(String utteranceId) {
        Log.i("Retain", "onDoneSpeaking");
        if (ultimoPlay.equals("")) {
            if (utteranceId.equals(ESTROFA[0])) {
                speakOut(tts02, TextToSpeech.QUEUE_FLUSH, ESTROFA[1]);
                mCallbacks.onFragmentRetainCambiaUltimoPlay("", ESTROFA[1]);

            } else if (utteranceId.equals(ESTROFA[1])) {
                speakOut(tts03, TextToSpeech.QUEUE_FLUSH, ESTROFA[2]);
                mCallbacks.onFragmentRetainCambiaUltimoPlay("", ESTROFA[2]);

            } //...
            } else if (utteranceId.equals(ESTROFA[20])) {
                mCallbacks.onFragmentRetainCambiaUltimoPlay("", ESTROFA[21]);

            }
        }
    }

    public static void onBackPressed() {
        Log.i("Retain", "onBackPressed");

        if (tts.isSpeaking()) {
            ultimoPlay = params.get(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID);
            tts.stop();

        }

        return;
    }

    @Override
    public void onDestroy() {
        Log.i("Retain", "onDestroy");
        // Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
}

0 个答案:

没有答案