最近遇到從網絡上下載圖片,解碼一直是null的問題:
- .....
- Bitmap bitmap=BitmapFactory.decodeStream(inputStream);
- ....
開始時以爲TimeOut太短,或者buffersize太小的問題,修改後仍然沒有解決問題,記得同樣的方法以前下載圖片挺正常的,Google之,找到了問題的答案,起碼解決了我的問題。
網上類似的問題:
原來是系統bug,2.1版本中仍存在這個問題:
http://code.google.com/p/android/issues/detail?id=6066
The problem was indeed in the calls to the InputStream skip() method.
解決方法:
- static class FlushedInputStream extends FilterInputStream {
- public FlushedInputStream(InputStream inputStream) {
- super(inputStream);
- }
- @Override
- public long skip(long n) throws IOException {
- long totalBytesSkipped = 0L;
- while (totalBytesSkipped < n) {
- long bytesSkipped = in.skip(n - totalBytesSkipped);
- if (bytesSkipped == 0L) {
- int bytes = read();
- if (bytes < 0) {
- break; // we reached EOF
- } else {
- bytesSkipped = 1; // we read one byte
- }
- }
- totalBytesSkipped += bytesSkipped;
- }
- return totalBytesSkipped;
- }
- }
或者另外建個類。
以前的代碼改爲:
- Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
遇到同樣問題的童鞋可以參考。