android.os.NetworkOnMainThreadException
在用KSOAP2包做WebService,在android 4.0上运行时报android.os.NetworkOnMainThreadException异常,原来在4.0中,访问网络不能在主程序中进行,有两个方法可以解决,一个是在主程序中增加:
1 // 详见StrictMode文档 2 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 3 .detectDiskReads() 4 .detectDiskWrites() 5 .detectNetwork() // or .detectAll() for all detectable problems 6 .penaltyLog() 7 .build()); 8 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 9 .detectLeakedSqlLiteObjects() 10 .detectLeakedClosableObjects() 11 .penaltyLog() 12 .penaltyDeath() 13 .build());
另一种是启动线程执行下载任务:
1 public void onCreate(Bundle savedInstanceState) { 2 super.onCreate(savedInstanceState); 3 setContentView(R.layout.main); 4 // 启动线程执行下载任务 5 new Thread(downloadRun).start(); 6 } 7 8 /** 9 * 下载线程 10 */ 11 Runnable downloadRun = new Runnable(){ 12 13 @Override 14 public void run() { 15 // TODO Auto-generated method stub 16 updateListView(); 17 } 18 };