Android Eclipseproject开发中的常见调试问题(二)android.os.NetworkOnMainThreadException 异常的解决的方法

android.os.NetworkOnMainThreadException 异常的解决的方法。

刚开是把HttpURLConnectionnection 打开连接这种方法放在UI线程里了,可能不是线程安全的,并且这种方法请求是须要等待的,所以就抛出了这个异常,后来用子线程打开的HttpURLConnection, 一切就都正常了。仅仅要在主线程里开启子线程即可了。

子线程利用URL

问题解决。以下贴一段代码

				String file1 = SERVER_PATH;
				URL url = new URL(file1);
				HttpURLConnection httpconn = (HttpURLConnection) url
						.openConnection();
				int responseCode = httpconn.getResponseCode();
				if (responseCode != HttpURLConnection.HTTP_OK) {
					Log.d(MP3, file1 + " server故障");
					mainHandler.sendEmptyMessage(NET_SERVER_ERROR);
				}
链接正常,返回200后。就能够打开流接受字节了。

InputStream is = httpconn.getInputStream(); BufferedReader bfr = new BufferedReader(new InputStreamReader(is));

...后面的就略去了


【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/zhchoutai/p/8919002.html