這是因爲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:立即查看源代碼。 –