AsyncTask的doInBackground中的android.os.NetworkOnMainThreadException

Sve*_*rer 6 android android-asynctask networkonmainthread

为什么我会进入一个应该是android.os.NetworkOnMainThreadException的AsyncTask?我认为AsyncTask是解决这个问题的方法.这个例外是在第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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想用它来下载图片.

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);
}
Run Code Online (Sandbox Code Playgroud)

ian*_*ake 15

通过doInBackground()直接调用,您实际上并未使用AsyncTask功能.相反,您应该调用execute(),然后通过覆盖AsyncTask的onPostExecute()方法来使用结果,如同一页面的Usage部分所述.