• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.tts;
18 
19 import android.app.Application;
20 import android.speech.tts.TextToSpeech;
21 import android.util.Pair;
22 
23 import androidx.lifecycle.AndroidViewModel;
24 
25 /**
26  * A helper view model to protect the TTS object from being destroyed and
27  * recreated on orientation change.
28 */
29 public class TextToSpeechViewModel extends AndroidViewModel {
30     private TextToSpeech mTts;
31 
32     // Save the application so we can use it as the TTS context
33     private final Application mApplication;
34 
TextToSpeechViewModel(Application application)35     public TextToSpeechViewModel(Application application) {
36         super(application);
37 
38         mApplication = application;
39     }
40 
41     /*
42      * Since the view model now controls the TTS object, we need to handle shutting it down
43      * ourselves.
44      */
45     @Override
onCleared()46     protected void onCleared() {
47         shutdownTts();
48     }
49 
shutdownTts()50     protected void shutdownTts() {
51         mTts.shutdown();
52         mTts = null;
53     }
54 
55     /*
56      * An accessor method to get the TTS object. Returns a pair of the TTS object and a boolean
57      * indicating whether the TTS object was newly created or not.
58      */
getTtsAndWhetherNew( TextToSpeech.OnInitListener listener)59     protected Pair<TextToSpeech, Boolean> getTtsAndWhetherNew(
60             TextToSpeech.OnInitListener listener) {
61         boolean ttsCreated = false;
62         if (mTts == null) {
63             mTts = new TextToSpeech(this.mApplication, listener);
64             ttsCreated = true;
65         }
66 
67         return Pair.create(mTts, ttsCreated);
68     }
69 
70 }
71