0

该应用程序在 2.2.1 和 2.2 上运行良好,但在 4.0.3 上导致以下错误

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
at libcore.io.IoBridge.recvfrom(IoBridge.java:503)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:161)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:175)
at org.apache.http.impl.io.ChunkedInputStream.exhaustInputStream(ChunkedInputStream.java:289)
at org.apache.http.impl.io.ChunkedInputStream.close(ChunkedInputStream.java:262)
at org.apache.http.conn.BasicManagedEntity.streamClosed(BasicManagedEntity.java:179)
at org.apache.http.conn.EofSensorInputStream.checkClose(EofSensorInputStream.java:266)
at org.apache.http.conn.EofSensorInputStream.close(EofSensorInputStream.java:213)
at java.io.FilterInputStream.close(FilterInputStream.java:64)
at java.util.zip.InflaterInputStream.close(InflaterInputStream.java:256)
at java.util.zip.GZIPInputStream.close(GZIPInputStream.java:148)
at com.myapp.apper.contact.ContactService.a(SourceFile:390)
at com.myapp.apper.contact.ContactService.a(SourceFile:347)
at com.myapp.apper.contact.ContactService.a(SourceFile:41)
at com.myapp.apper.contact.g.a(SourceFile:322)
at com.myapp.apper.contact.q.a(SourceFile:58)
at com.myapp.apper.contact.q.onPostExecute(SourceFile:23)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4974)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

我所有的网络操作都在 AsyncTask 中,从堆栈跟踪看起来错误是由它引起的java.util.zip.GZIPInputStream.close,它也指向类似 390 的代码,即gzipIn.close();.

GZIPInputStream 是否会导致此错误?如果不是,错误的原因可能是什么?

4

1 回答 1

3

看起来您正在使用 GZIPInputStreamonPostExecute()在 UI 线程中运行的异步任务中读取某些内容。从 4.0 开始,UI 线程中不允许有网络连接。我建议在doInBackground()方法中移动 GZIPInputStream 读取部分。

Edit1:或者您可以通过以下代码禁用严格模式:

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = 
        new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
于 2012-11-02T18:23:37.567 回答