为什么我会进入一个应该是
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,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); }