`
piperzero
  • 浏览: 3473619 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

安卓3.0之后的网络访问问题

 
阅读更多

在Activity中使用如下web请求

  1. Stringurl="http://maps.google.com/maps/api/directions/xml?origin=22.592700,113.969100"+
  2. "&destination=23.046604,113.397510&sensor=false&mode=walking";
  3. HttpGetget=newHttpGet(url);
  4. StringstrResult="";
  5. try{
  6. HttpParamshttpParameters=newBasicHttpParams();
  7. HttpConnectionParams.setConnectionTimeout(httpParameters,6000);
  8. HttpClienthttpClient=newDefaultHttpClient(httpParameters);
  9. HttpResponsehttpResponse=null;
  10. httpResponse=httpClient.execute(get);
  11. if(httpResponse.getStatusLine().getStatusCode()==200){
  12. strResult=EntityUtils.toString(httpResponse.getEntity());
  13. }
  14. }catch(Exceptione){
  15. e.printStackTrace();
  16. }

发现请求总是无法得到,在浏览器中尝试发现请求语句没有问题

DDMS报错为:android.os.NetworkOnMainThreadException

经查询发现原来Android3.0以上对网络请求做了更严格的限制,若要继续按照以前的方式继续使用网络请求,须做一些特别的声明。

解决办法:

在Activiey的OnCreate方法中添加以下代码

  1. StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
  2. .detectNetwork()//or.detectAll()foralldetectableproblems
  3. .penaltyLog()
  4. .build());
  5. StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics