我正在使用http://android-developers.blogspot.gr/2010/07/multithreading-for-performance.html的代碼與http://developer.android.com/training/displaying-bitmaps/index.html代碼的組合。當我嘗試從網址下載圖像異步而不更改樣本大小的一切都沒事。但是當我嘗試計算樣本大小時,屏幕上沒有任何東西出現(gridview)。我讀了logcat,我發現所有的圖像都正確下載。我使用的圖像下載的代碼是下一個:gridview異步下載
Bitmap downloadBitmap(String url) {
final HttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
// get Device Screen Dimensions
DeviceProperties dimensions = new DeviceProperties(activity);
return
decodeBitmapFromResource(url, inputStream,
dimensions.getDeviceWidth(),
dimensions.getDeviceHeight());
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
getRequest.abort();
Log.w(TAG, "I/O error while retrieving bitmap from " + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(TAG, "Incorrect URL: " + url);
} catch (Exception e) {
getRequest.abort();
Log.w(TAG, "Error while retrieving bitmap from " + url, e);
} finally {
if ((client instanceof AndroidHttpClient)) {
((AndroidHttpClient) client).close();
}
}
return null;
}
,我使用解碼的代碼是這樣的:
public static Bitmap decodeBitmapFromResource(String url, InputStream is,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FlushedInputStream(is), null,
options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options , reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(new FlushedInputStream(is), null,
options);
}
當我使用這兩個第一次出現問題和第二個BitmapFactory.decodeStream。如果我只使用第二個,那麼一切都可以,但實際上我不做任何樣本。任何建議?我失去了很多時間尋找它。
是否使用byteArrayOutputStream更好的解決方案? – userX
您進行雙通道的原因是通過分配大內存來避免OutOfMemory異常一個。如果你使用一個字節數組,你將會分配內存。 – Budius
你是對的!謝謝。 – userX