【发布时间】:2014-10-06 20:06:07
【问题描述】:
为什么我会进入一个应该是 android.os.NetworkOnMainThreadException 的 AsyncTask?我认为 AsyncTask 是该问题的解决方案。 exxeption 在第 7 行。
private class ImageDownloadTask extends AsyncTask<String, Integer, byte[]> {
@Override
protected byte[] doInBackground(String... params) {
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
} catch (IOException ex) {
return new byte[0];
}
}
}
我想用它来下载图片。
public byte[] getProfilePicture(Context context, String id) {
String url = context.getString(R.string.facebook_picture_url_large, id);
ImageDownloadTask task = new ImageDownloadTask();
return task.doInBackground(url);
}
【问题讨论】:
-
添加调用AsyncTask的代码
-
没有重复,因为所有帖子都是关于没有使用异步任务的帖子,但我有并且得到了例外。
-
您需要在 AsyncTask 上调用 .execute() 才能使其在后台工作。 developer.android.com/reference/android/os/AsyncTask.html
标签: android android-asynctask networkonmainthread