这是因为AsyncTask
等待计算get()
方法在doInBackground
方法完成,然后获取其结果。看到这个link。
这将使你的主要在UIThread
等待模式,直到doInBackground
完成它的执行还是有一些例外发生(即。CancellationException
,ExecutionException
和InterruptedException
)。
您应该使用onPostExecute(Result)
替代方法AsyncTask
。
private class OkHttpHandler extends AsyncTask<String, Void, byte[]> {
OkHttpClient client = new OkHttpClient();
@Override
protected byte[] doInBackground(String... params) {
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
return response.body().bytes();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
try {
if (bytes != null && bytes.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(bitmap);
tv.setText("Total btytes download: " + bytes.length);
}
} catch (Exception e) {
tv.setText("sorry, something went wrong!");
}
}
}
我没有在任何地方使用Thread.sleep()或wait()。 –
你能分享一些代码吗? – M4R1KU
@ M4R1KU:立即查看源代码。 –