android.os.NetworkOnMainThreadException fixed
来源:互联网 发布:windows 自动运行程序 编辑:程序博客网 时间:2024/06/10 11:10
出现这个错误,当时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(){@Overridepublic void run() {// TODO Auto-generated method stubString 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};thread.start();在开发过程中,用到了访问网络的权限,故要在AndroidManifest.xml 当中添加<uses-permission android:name="android.permission.INTERNET"/> 权限
0 0
- android.os.NetworkOnMainThreadException fixed
- android.os.NetworkOnMainThreadException问题
- android.os.NetworkOnMainThreadException问题
- android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException异常
- 关于android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException
- 异常:android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException异常
- android.os.NetworkOnMainThreadException
- exception: android.os.NetworkOnMainThreadException
- 异常:android.os.NetworkOnMainThreadException
- android.os.NetworkOnMainThreadException
- 鼎力支持地球一小时,点心移动彰显移动互联网“社会责任感”
- 使用 udev 高效、动态地管理 Linux 设备文件
- CreateEvent()的用法
- Java SSL 服务器 客户端通信 试用
- 冠心病胸闷气短不需要再做心脏支架手术了
- android.os.NetworkOnMainThreadException fixed
- 有关epoll读写监听的处理
- NSUnknownKeyException', reason: '[<UIApplication 0x8a58320> setValue:forUndefinedKey:]
- boa web服务器移植
- 在ubuntu 12.04上安装android sdk及配置jdk开发环境
- 位运算介绍
- Struts-Menu角色权限的实例代码
- windows bat脚本编写
- 近期汇总的PHP小技巧