问题描述
为什么我得到一个AsyncTask的,应一android.os.NetworkOnMainThreadException?我认为,一个AsyncTask的是解决这个问题。该exxeption是第7行。
私有类ImageDownloadTask扩展的AsyncTask<字符串,整数,字节[]> {
@覆盖
受保护的byte [] doInBackground(字符串... PARAMS){
尝试 {
网址URL =新的URL(PARAMS [0]);
URLConnection的连接= url.openConnection();
InputStream中的InputStream = connection.getInputStream();
ByteArrayOutputStream的ByteBuffer =新ByteArrayOutputStream();
INT缓冲区大小= 1024;
byte []的缓冲区=新的字节[BUFFERSIZE]
INT LEN;
而((LEN = inputStream.read(缓冲液))!= - 1){
byteBuffer.write(缓冲液,0,LEN);
}
返回byteBuffer.toByteArray();
}赶上(IOException异常前){
返回新的字节[0];
}
}
}
我想用它来下载图片。
公共字节[] getProfilePicture(上下文的背景下,字符串ID){
字符串URL = context.getString(R.string.facebook_picture_url_large,ID);
ImageDownloadTask任务=新ImageDownloadTask();
返回task.doInBackground(URL);
}
通过调用 doInBackground()
直接,你实际上并没有使用AsyncTask的功能。相反,你应该叫execute()然后通过覆盖AsyncTask的的onPostExecute()方法在同一页的用法如下一节。
Why do I get in an AsyncTask which should a android.os.NetworkOnMainThreadException? I thought that an AsyncTask is the solution to that problem. The exxeption is on line 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];
}
}
}
I want to use it for downloading a picture.
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);
}
By calling doInBackground()
directly, you are not actually using the AsyncTask functionality. Instead, you should call execute() and then use the results by overriding the AsyncTask's onPostExecute() method as explained in the Usage section of that same page.
这篇关于android.os.NetworkOnMainThreadException中的AsyncTask的doInBackground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!