在2.2系统下开发的程序运行在4.0系统时报android.os.NetworkOnMainThreadException异常,经过查文档,原来是4.0系统不允许主线程(UI线程)访问网络,因此导致了其异常。
参考文档连接
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
解决方法1:
- public void onCreate() {
- if (DEVELOPER_MODE) {
- StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
- .detectDiskReads()
- .detectDiskWrites()
- .detectNetwork() // or .detectAll() for all detectable problems
- .penaltyLog()
- .build());
- StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
- .detectLeakedSqlLiteObjects()
- .detectLeakedClosableObjects()
- .penaltyLog()
- .penaltyDeath()
- .build());
- }
- super.onCreate();
- }
注意:由于StrictMode 是android 2.3才开始提供,所以当你把程序运行在2.2时就会报错,所以在你调用StrictMode 时最好来个系统版本判断,当系统版本大于2.3时才调用StrictMode
参考文档连接
http://developer.android.com/reference/android/os/StrictMode.html
解决方法2:
开线程处理关于网络的事物,然后用handler发送消息来处理更新UI