android.os.NetworkOnMainThreadException 异常处理

当我试图在UI线程(MainActivity)连接网络的时候,运行时抛出异常droid.os.NetworkOnMainThreadException 

安卓的官方文档说

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.

基于减少UI线程耗时操作的考虑,安卓3.0以上不再允许在UI线程上进行网络连接。

解决方法

1.使用Strict Mode 强行在UI线程连接,(官方不推荐)

2.开一个线程进行网络连接,再用Handler将结果传给UI线程。