gpt4 book ai didi

java - Android Studio 错误 : "Method getText must be called from the UI Thread, 当前推断线程为工作线程

转载 作者:行者123 更新时间:2023-12-02 12:56:15 24 4
gpt4 key购买 nike

我遇到了有关 gettext() 的问题,Android studio 说“必须从 UI 线程调用方法 getText,当前推断的线程是工作线程”。有人可以帮助我解决这个问题,或者有人可以提供如何解决这个问题的想法吗?谢谢!

package com.ibm.watsonvoicetts;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;

public class MainActivity extends AppCompatActivity {

TextView textView;
EditText editText;
Button button;

StreamPlayer streamPlayer;


private TextToSpeech initTextToSpeechService(){
TextToSpeech service = new TextToSpeech();
String username = "";
String password = "";
service.setUsernameAndPassword(username, password);
return service;
}

private class WatsonTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... textToSpeak) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("running the Watson thread");
}
});

TextToSpeech textToSpeech = initTextToSpeechService();
streamPlayer = new StreamPlayer();
streamPlayer.playStream(textToSpeech.synthesize(
String.valueOf(editText.getText()),【**here is the problem**】
Voice.EN_MICHAEL).execute());

return "text to speech done";
}

@Override
protected void onPostExecute(String result) {
textView.setText("TTS status: " + result);
}

}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("the text to speech: " + editText.getText());
textView.setText("TTS: " + editText.getText());

WatsonTask task = new WatsonTask();
task.execute(new String[]{});


}
});
}

}

最佳答案

您不应该像您正在做的那样从 AsyncTask 调用 getText。解决方案是将值传递到任务的构造函数中。

改变

WatsonTask task = new WatsonTask(editText.getText());

private class WatsonTask extends AsyncTask<String, Void, String> {
private final String text;
public WatsonTask(String text) {
super();
this.text = text;
}

streamPlayer.playStream(textToSpeech.synthesize(
String.valueOf(text),
Voice.EN_MICHAEL).execute());

关于java - Android Studio 错误 : "Method getText must be called from the UI Thread, 当前推断线程为工作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44426210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com