出现这个错误,当时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"/> 权限