本文介绍了OkHTTP从入队回调中更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用OkHTTP库.呼叫服务器并获得成功的响应时.我需要更新用户界面.
I am trying to use OkHTTP library. When making a call to the server and getting a successful response back. i need to update the UI.
使用enqueue()进行异步调用时怎么办?
How can this be done when doing an Async call using the enqueue()?
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
// NEED TO UPDATE UI HERE
}
}
});
推荐答案
您可以参考以下示例代码,希望对您有所帮助!
You can refer to the following sample code, hope this helps!
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "OkHttp";
private TextView mTextView;
private Handler mHandler;
private String mMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView);
mHandler = new Handler(Looper.getMainLooper());
OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
.url("http://...")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
mMessage = e.toString();
Log.e(LOG_TAG, mMessage); // no need inside run()
mHandler.post(new Runnable() {
@Override
public void run() {
mTextView.setText(mMessage); // must be inside run()
}
});
}
@Override
public void onResponse(Response response) throws IOException {
mMessage = response.toString();
Log.i(LOG_TAG, mMessage); // no need inside run()
mHandler.post(new Runnable() {
@Override
public void run() {
mTextView.setText(mMessage); // must be inside run()
}
});
}
});
}
}
这篇关于OkHTTP从入队回调中更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!