android.os.NetworkOnMainThreadException与android 4.2

在这里,我使用这个代码加载Json。 这是工作正常与android 2.2,但是当我使用android 4.2它抛出android.os.NetworkOnMainThreadExceptionexception,请给我解决scheme

public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(url); HttpResponse getResponse = httpClient.execute(httpPost); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); //HttpResponse httpResponse = httpClient.execute(httpPost); //HttpEntity httpEntity = httpResponse.getEntity(); is = getResponseEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { Log.d("IO", e.getMessage().toString()); e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } 

}

我也使用谷歌API。

在setContentView(R.layout.activity_main)之后将代码写入到MainActivity文件中;

 if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } 

并将下面的import语句导入到你的java文件中。

 import android.os.StrictMode; 

这是正确的方法:

 public class JSONParser extends AsyncTask <String, Void, String>{ static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } @Override protected String doInBackground(String... params) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(url); HttpResponse getResponse = httpClient.execute(httpPost); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); //HttpResponse httpResponse = httpClient.execute(httpPost); //HttpEntity httpEntity = httpResponse.getEntity(); is = getResponseEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { Log.d("IO", e.getMessage().toString()); e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } protected void onPostExecute(String page) { //onPostExecute } } 

从(主)调用它:

 mJSONParser = new JSONParser(); mJSONParser.execute(); 

请确保您不会在UI线程上执行任何networking访问,而是在“ asynchronous任务”中执行此操作

之所以你的应用程序崩溃的Android 3.0及以上版本,但工作正常的Android 2.x是因为,因为HoneyComb更严格的UI线程滥用。 例如,当运行HoneyComb或更高版本的Android设备在UI线程上检测到networking访问时,将引发NetworkOnMainThreadException。

看到这个

使用StrictMode这样的东西: –

  if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } 

当您尝试访问您的主线程上的networking(您主要活动执行)时,会发生android.os.NetworkOnMainThreadException 。 为了避免这种情况,您必须创build一个单独的线程或AsyncTaskRunnable实现来执行您的JSON数据加载。 由于HoneyComb不能在主线程上进一步执行networking任务。 这里是使用AsyncTask执行networking任务的实现