我是Java新手。 如您所见,此代码阻止了ui线程。当它运行时,应用程序冻结直到完成运行(它不会弹出ANR)我需要在此代码运行时为进度按钮设置动画。有什么想法吗?
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onSpeechButtonClicked (View v) {
TextView outputMessage = this.findViewById(R.id.outputMessage);
EditText speakText = this.findViewById(R.id.speakText);
try {
// Note: this will block the UI thread, so eventually, you want to register for the event
SpeechSynthesisResult result = synthesizer.SpeakText(speakText.getText().toString());
assert(result != null);
if (result.getReason() == ResultReason.SynthesizingAudioCompleted) {
((LoadingButton) findViewById(R.id.button_test)).stopLoading("SPEAK");
outputMessage.setText("Speech synthesis succeeded.");
System.out.println("Synthesis succeeded.");}
else if (result.getReason() == ResultReason.Canceled) {
String cancellationDetails =
SpeechSynthesisCancellationDetails.fromResult(result).toString();
((LoadingButton)findViewById(R.id.button_test)).stopLoading("There was a problem...");
outputMessage.setText("Error synthesizing. Error detail: " +
System.lineSeparator() + cancellationDetails +
System.lineSeparator() + "Did you update the subscription info?");
}
result.close();
} catch (Exception ex) {
Log.e("SpeechSDKDemo", "unexpected " + ex.getMessage());
assert(false);
}
}
答案 0 :(得分:0)
您可以在代码中使用asynctasks。另外,您可以在runOnUiThread()中使用可运行线程或新线程。将不会提供任何代码,因为Internet中有很多示例。
答案 1 :(得分:0)
感谢Johny Deph,这就是我修复代码的方式。希望其他人也能找到帮助。
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onSpeechButtonClicked (View v) {
final TextView outputMessage = this.findViewById(R.id.outputMessage);
final EditText speakText = this.findViewById(R.id.speakText);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
synchronized (this){
try {
SpeechSynthesisResult result = synthesizer.SpeakText(speakText.getText().toString());
assert(result != null);
if (result.getReason() == ResultReason.SynthesizingAudioCompleted) {
((LoadingButton) findViewById(R.id.button_test)).stopLoading("SPEAK");
outputMessage.setText("Speech synthesis succeeded.");
System.out.println("Synthesis okuur started.");}
else if (result.getReason() == ResultReason.Canceled) {
String cancellationDetails =
SpeechSynthesisCancellationDetails.fromResult(result).toString();
((LoadingButton)findViewById(R.id.button_test)).stopLoading("There was a problem...");
outputMessage.setText("Error synthesizing. Error detail: " +
System.lineSeparator() + cancellationDetails +
System.lineSeparator() + "Did you update the subscription info?");
}
result.close();
} catch (Exception ex) {
Log.e("SpeechSDKDemo", "unexpected " + ex.getMessage());
assert(false);
}
}
}
});
t.start();