我正在尝试使用OkHTTP库。调用服务器并获得成功响应时。我需要更新UI。
使用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
}
}
});
答案 0 :(得分:16)
您可以参考以下示例代码,希望这有帮助!
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()
}
});
}
});
}
}
答案 1 :(得分:6)
答案 2 :(得分:5)
Try this:
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
// code to interact with UI
}
});
答案 3 :(得分:1)
为了拥有干净的代码,我建议你不要将整个代码放在runnable中。
一个简单的例子:
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://...").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Response response) throws IOException {
final String body = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
updateUI(body);
}
});
}
});
}
private void updateUI(responseBody){
//TODO: update your UI
}
}