Reputation: 2535
I am having a strange experience with text to speech.
see my code:
Button b;
TextView title, body;
TextToSpeech tts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popups);
b = (Button) findViewById(R.id.buttonok);
title = (TextView) findViewById(R.id.textViewtitle);
body = (TextView) findViewById(R.id.textViewbody);
b.setText("ok");
title.setText(Receive.address);
body.setText(Receive.body);
tts = new TextToSpeech(Popup.this, new TextToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.US);
}
}
});
play();//this is not working??!!i don't know why
b.performClick();//even this is not working
/* but when i click this button it works??? how and why?*/
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play(); // Popup.this.finish();
}
});
}
private void play() {
// TODO Auto-generated method stub
tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);
}
My text to speech works fine only when i click the button but whenever i don't click this button and write the tts.speak() inside normal code it do not works...why?
regards charlie
Upvotes: 3
Views: 482
Reputation: 11185
b.performClick();//even this is not working
/* but when i click this button it works??? how and why?*/
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play(); // Popup.this.finish();
}
});
You are performing a click with b.performClick()
before setting its setOnClickListener
. Also, you are better off making such calls on the onResume()
method. OnCreate is meant to be used to bind views and prepare the activity. The onResume()
method will be called before showing the view to the user on the foreground so that would be the best place to put this code.
Take a look at the activity lifecycle.
Upvotes: 2
Reputation: 18151
You have to wait for onInit
being called before you can start speak
. In your code you call play() right after the declaration. onInit is a callback and it takes some time before it being called. If you click your button as soon as the button appears, sometime it will fail as onInit has not been called. You should have a class member boolean mIsReady
and set it to true in onInit. And in your play()
method
private void play() {
// TODO Auto-generated method stub
if (mIsReady) {
tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);
}
}
Upvotes: 4