Android Honeycomb:即使使用 AsyncTask 并且没有严格模式,也会出现 NetworkOnMainThreadException?
我的 Android 3.0 应用程序遇到 NetworkOnMainThreadException 。 在寻找解决方案时,我发现这个,但如果我理解正确的话,默认设置是关闭严格模式。
另外,我所有的网络访问都在 AsyncTask
中,所以无论如何我都看不到这个异常的意义。
所以,我现在非常绝望,我应该做什么来防止这种情况......
亲切的问候, jellyfish
编辑:
此博客条目说AsyncTask应该足够了,但至少澄清了StrictMode点。
解决方案:
我关闭了 StrictMode(保留一些设置可能会更好,但我不会被打扰......):
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
之后,我确实遇到了“java.lang.RuntimeException:这线程禁止 HTTP 请求”,但在此处找到了解决方案。不过,我有点困惑,因为当我在 Android 2.0+ 应用程序中使用 AndroidHttpClient
时,它工作得很好...
解决方案,第 2 部分
事实证明,使用 AsyncTask是一个好主意,但如果做错了,则毫无用处。 。 所以严格模式的反应并没有什么问题。应该听的,呃? ;)
很高兴知道它默认在 Honeycomb 上激活。
I run into a NetworkOnMainThreadException with my Android 3.0 app.
Searching for a solution I found this, but if I understand this correctly, default setting would be that the strict mode is turned off.
Also, all my network access is in an AsyncTask
, so I don't see the point in this Exception anyway.
So, I'm quite desperate now what I should do to prevent this...
Kind regards,
jellyfish
Edit:
This blog entry says that AsyncTask should be enough, but at least clarifies the StrictMode point.
Solution:
I turned off the StrictMode (its probably better to keep some settings but I couldn't be bothered...):
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
After that, I did run into a "java.lang.RuntimeException: This thread forbids HTTP requests", but found a solution for this here. I'm a bit confused, though, as AndroidHttpClient
worked fine when I used it in my Android 2.0+ app...
Solution, part2
As it turned out, using AsyncTask was a nice idea but pretty useless if done wrong...
So there was nothing wrong with the strict mode's reaction. Should have listened, er? ;)
Still good to know it's activated on Honeycomb by default.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Android Honeycomb StrictMode 启用时,将其关闭,在 onCreate() 函数上添加代码...
In Android Honeycomb StrictMode is enabled, turn it off adding the code on the onCreate() function...
Honeycomb 中默认启用 StrictMode。
具体请参阅链接
惩罚DeathOnNetwork()。我遇到了类似的问题。
StrictMode is turned on by default in Honeycomb.
See say link specifically
penaltyDeathOnNetwork()
. I ran into a similar problem.