andriod访问网络出现NetworkOnMainThreadException解决方法
為什么80%的碼農都做不了架構師?>>> ??
##訪問網絡## andriod應用在進行網絡訪問時,需要在Manifest文件中加入權限訪問允許:
<!-- lang: xml --> <uses-permission android:name="android.permission.INTERNET"/>否則會拋出異常。
在C8815手機上進行測試,寫一個Client端與Mini2440開發板上C寫的的Server進行Socket通信。應用出現閃退。而用這種調試模式無法顯示調試信息,只是提示無法捕捉異常。
于是安裝Genmotion模擬器進行調試。具體介紹和安裝方法見http://www.genymotion.com/。
安裝模擬器后,eclipse出現錯誤信息。
android.os.NetworkOnMainThreadException
在這里找到解決方法。
在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代碼
<!-- lang: java --> if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }Client和Server能正常進行通信。
這個異常出現的原因是:
The exception that is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness. Also see StrictMode.
簡單地說,就是一個APP如果在主線程中請求網絡操作,將會拋出此異常。Android這個設計是為了防止網絡請求時間過長而導致界面假死的情況發生。關于 StrictMode類控制,請見[2]。
##References## [1].http://www.2cto.com/kf/201402/281526.html [2].http://hb.qq.com/a/20110914/000054.htm
轉載于:https://my.oschina.net/lvyi/blog/271309
總結
以上是生活随笔為你收集整理的andriod访问网络出现NetworkOnMainThreadException解决方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 推荐一款基于web的Unix系统管理工具
- 下一篇: Wordcount on YARN 一个