这是我正在处理的代码。在我的OnResponse
完成之前,我无法更新用户界面。因为我们正在执行doInBackgrnd
,所以我的textresponse
为空。由于onPostExecute
正在发生。
对于他,我认为PublicProgres应该有所帮助。 如何在AsyncTask上调用PublishProgress?
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
@Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
@Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
action5(textResponse);
System.out.println(textResponse);
}
@Override
public void onFailure(Exception e) {
}
});
return textResponse;
}@Override protected void onPostExecute(String result) {
reply.setText(textResponse);
}
}
请帮忙。
答案 0 :(得分:2)
我认为您不必使用AsyncTask
。
您可以这样做:
YourTask.java
public class YourTask implements Runnable {
private Handler handler;
private TextView textView;
public YourTask(TextView textView){
this.textView = textView;
handler = new Handler();
}
@Override
public void run() {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
@Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
@Override
public void run() {
if(textView != null){
textView.setText(textResponse);
}
}
});
}
@Override
public void onFailure(Exception e) {
}
});
}
}
现在如何使用它:
SomeActivity.java
...
textView = (TextView) findViewById(R.id.textView);
...
Thread thread = new Thread(new YourTask(textView));
thread.start();
...
然而,如果您想在Asynktask
中执行此操作,请尝试此操作
private class ConversationTask extends AsyncTask<String, Void, Void> {
private Handler handler;
public ConversationTask(){
handler = new Handler();
}
@Override
protected Void doInBackground(String... params) {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
@Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
@Override
public void run() {
if(reply != null){
reply.setText(textResponse);
}
}
});
}
@Override
public void onFailure(Exception e) {
}
});
return null;
}
}
希望有所帮助