所以我有一个问题。我正在尝试让我的应用根据通过GCM收到的消息来执行操作。在这种情况下,应该使用TextToSpeech类发出声音。有点用,但不是我第一次发送邮件。我意识到这可能是因为尚未实例化TextToSpeech,但是我不确定该怎么做?我尝试了onInit(),但这根本不起作用。
另外,在我的示例中,关闭TTS的最佳方法是什么?
免责声明:我来自PHP背景,对Java的了解很少。我尝试边做边学,所以如果这是一个愚蠢的问题,请原谅我。提前致谢!public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public static TextToSpeech mtts;
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("message");
mtts = new TextToSpeech(context, null);
if (message.startsWith("makeSound")) {
mtts = new TextToSpeech(context, null);
mtts.setLanguage(Locale.US);
mtts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
最佳答案
第一次不能使用,因为TextToSpeech的初始化是异步的。您不能简单地实例化它并按需使用它。如果您想立即使用TextToSpeech,则应提供一个一旦初始化TextToSpeech即可调用的回调。mTextToSpeech = new TextToSpeech( this, new TextToSpeech.OnInitListener()
{
@Override
public void onInit( int status )
{
// Check for status might not be initialized due to errors
// Configure language/speed
}
} );
其余时间都可以使用,因为mtts是静态的。这意味着这是一个类变量,在创建服务的新实例时不会被破坏/初始化。第二次使用该服务时,该变量已在第一次服务执行中初始化。