android.os.NetworkOnMainThreadException fixed

出现这个错误,当时google了一下,问题是Android 4.0以后的版本中主线程不能直接采用异步请求相应的方式来取数据,我想google这么设计也是为了更好的提升用户体验吧!
解决这个问题有两个办法可以来使用:

1.

setContentView(R.layout.activity_main);
		/*if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}*/
在MainActivity中加我注释的代码是能解决这个问题的,但不是最佳实践。

StrictMode 参照:http://chriszeng87.iteye.com/blog/1958564

2.添加另外一个线程也能解决这个问题:

Thread thread = new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false";
				HttpClient httpClient = new DefaultHttpClient();
				String responseData = "";
				//向指定的URL发送http请求,相应数据放在response 里面
				HttpResponse response;
				try {
					response = httpClient.execute(new HttpGet(url));
					HttpEntity entity = response.getEntity();
					BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
					String line = "";
					while ((line = bufferedReader.readLine()) != null) {
						responseData = responseData + line;
					}
					Log.i("location06", "responseData:"+responseData);
					TestResult testResult = JSON.parseObject(responseData, TestResult.class);
					Log.i("location06", testResult.toString());
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		thread.start();
在开发过程中,用到了访问网络的权限,故要在AndroidManifest.xml  当中添加<uses-permission android:name="android.permission.INTERNET"/> 权限

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值