我在android.below中从url获取图片时出现OutOfMemoryError我提到了我的代码和异常。
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
URL url = null;
try {
url = new URL(image);
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 )
{
bais.write(byteChunk, 0, n);
}
is.close();
bais.flush();
} catch (Exception e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
bais = null; // Perform any other exception handling that's appropriate.
}
异常日志:为上述代码生成
03-22 13:04:44.858: E/dalvikvm-heap(1528): Out of memory on a 13131140-byte allocation. 03-22 13:04:44.858: I/dalvikvm(1528):
> "Thread-180" prio=5 tid=25 RUNNABLE 03-22 13:04:44.858:
> I/dalvikvm(1528):|group="main" sCount=0 dsCount=0
> obj=0x415deed8self=0x378150 03-22 13:04:44.858: I/dalvikvm(1528): |
> sysTid=1572 nice=0 sched=0/0 cgrp=[fopen-error:2]handle=1723384 03-22
> 13:04:44.858: I/dalvikvm(1528): | schedstat=( 765401358 258475984 4706
> ) utm=41 stm=35 core=0 03-22 13:04:44.858: I/dalvikvm(1528): at
> java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:~91)
> 03-22 13:04:44.858: I/dalvikvm(1528): at
> java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
> 03-22 13:04:44.858: I/dalvikvm(1528): at
> com.lukup.util.FetchImage.run(FetchImage.java:46) 03-22 13:04:44.858:
> W/dalvikvm(1528): threadid=25: thread exiting with uncaught
> exception(group=0x409df1f8) 03-22 13:04:44.868:
> E/AndroidRuntime(1528): FATAL EXCEPTION: Thread-180 03-22
> 13:04:44.868: E/AndroidRuntime(1528): java.lang.OutOfMemoryError 03-22
> 13:04:44.868: E/AndroidRuntime(1528): at
> java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
> 03-22 13:04:44.868: E/AndroidRuntime(1528): at `enter code
> here`java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
> 03-22 13:04:44.868: E/AndroidRuntime(1528): at
> com.lukup.util.FetchImage.run(FetchImage.java:46)
> --
以上是异常日志
答案 0 :(得分:0)
您正在尝试进行13 MB的分配。有些手机不会让应用程序使用那么多的内存总量,忘记一次分配 - 即使很多新手机都会失败。尝试更频繁地刷新输出流,可能是它是愚蠢的,并保持整个输出的内存,直到它被刷新。