android.os.NetworkOnMainThreadException 异常处理

第一种在主程序中增加:

//安卓2.3以后访问网络增加内容  
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
                    .detectDiskReads()  
                    .detectDiskWrites()  
                    .detectNetwork()  
                    .penaltyLog()  
                    .build());   
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
                    .detectLeakedSqlLiteObjects()  
                    .detectLeakedClosableObjects()  
                    .penaltyLog()  
                    .penaltyDeath()  
                    .build());

第二种采用异步方式:

private class GeocodeingOnclickListener implements OnClickListener{  
        @Override  
        public void onClick(View v) {  
            new GeocodeingTask().execute();  
        }  
    }  
    private class GeocodeingTask extends AsyncTask<Integer, Integer, Integer>{  
        @Override  
        protected Integer doInBackground(Integer... params) {  
            String url="http://maps.googleapis.com/maps/api/geocode/json?" +  
                    "latlng=35.95405270,117.30649970&sensor=false";  
            //创建一个Httpclient对象  
            HttpClient httpClient=new DefaultHttpClient();  
            String responseData="";  
            try {  
                //向指定的Http地址发送请求  
                HttpResponse httpResponse=httpClient.execute(new HttpPost(url));  
                //取得服务器返回的响应  
                HttpEntity httpEntity=httpResponse.getEntity();  
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(httpEntity.getContent()));  
                String line="";  
                while((line=bufferedReader.readLine())!=null){  
                    responseData=responseData+line;  
                }  
            } catch (ClientProtocolException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            Gson gson=new Gson();  
            TestResult result=gson.fromJson(responseData, TestResult.class);  
            System.out.println(result.toString());  
            return null;  
        }  
    }

第三种采用线程的方式(与第二种类似 都是异步的方式) 

super.onCreate(savedInstanceState);  
      setContentView(R.layout.main);  
      // 启动线程执行下载任务  
      new Thread(downloadRun).start();  
  }  
    
  /** 
   * 下载线程 
   */  
  Runnable downloadRun = new Runnable(){  
  
@Override  
public void run() {  
    // TODO Auto-generated method stub  
    updateListView();  
}  
  };

 

你可能感兴趣的:(android.os.NetworkOnMainThreadException 异常处理)