代码之家  ›  专栏  ›  技术社区  ›  nidhin

IntetentService中的NetworkOnMainThreadException

  •  1
  • nidhin  · 技术社区  · 13 年前

    我有一个IntentService可以执行网络操作(HTTPPOST),但它显示NetworkOnMainThreadException。如果我是对的,IntentService将在一个单独的线程上运行。有人能说出为什么会抛出这个异常吗?我的代码是:

    public class UpdateService extends IntentService {
    public static final int UPDATE_PROGRESS = 8344;
    BroadcastReceiver broadcastReceiver;
    public UpdateService() {
        super("UpdateService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
    
            if (broadcastReceiver == null) {
    
                broadcastReceiver = new BroadcastReceiver() {
    
                    @Override
                    public void onReceive(Context context, Intent intent) {
    
                        Bundle extras = intent.getExtras();
    
                        NetworkInfo info = (NetworkInfo) extras.getParcelable("networkInfo");
    
                        State state = info.getState();
                        if (state == State.CONNECTED) {
    
                            onNetworkUp();
    
                        } else {
    
                        }
                    }
                };
    
                final IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                registerReceiver(broadcastReceiver, intentFilter);
            }
    }
    
    @Override
    public void onDestroy(){
        unregisterReceiver(broadcastReceiver);
        }
    
    void onNetworkUp(){
        String aDataRow = "";
        try {
            File myFile = new File( Environment.getExternalStorageDirectory().getPath() + "/myFile.txt");
            FileReader fr = new FileReader(myFile);
            BufferedReader myReader = new BufferedReader(fr);   
            while ((aDataRow = myReader.readLine()) != null) 
            updateLyne(aDataRow); //
            fr.close();
        } catch (Exception e) {
            Log.e("onNetworkUp",e.toString());
        }   
    
    
        void updateLyne(String aDataRow){
        JSONParser jsonParser = new JSONParser();
        String[] words = aDataRow.split(" ");
        pid = words[1];
        String rtime = aDataRow;
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_PID, pid));
        params.add(new BasicNameValuePair(TAG_TIME, rtime));
    
        JSONObject json = null;
        if (words[0].equalsIgnoreCase("cancel")){
            json = jsonParser.makeHttpRequest(url_cancel, "POST", params);                  
        }
        else{
            Log.d("empty","file empty!!");
        }
    
        try {
            int success = json.getInt("success");
    
            if (success == 1) {
                delLine(aDataRow); // delete the line
            } else {
                Log.d("pid="+pid+" not on board", "failed in deleting");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
    }
    }
    

    下面给出了JSONParser.java

        public class JSONParser {
    
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    
    // constructor
    public JSONParser() {
    
    }
    
    // function get json from url
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
    
        // Making HTTP request
        try {
    
            // check for request method
            if(method == "POST"){
    
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            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;
    
    }
        }
    
    1 回复  |  直到 13 年前
        1
  •  1
  •   Egor    13 年前

    问题是您没有在中运行网络请求 onHandleIntent() ,您只是在创建 BroadcastReceiver 并注册它。实际的网络请求不会在那里运行。当 广播接收机 接收一条消息,该消息发生在UI线程上。这里的一个正确方案是创建 广播接收机 在其他地方,当收到消息时,启动 IntentService ,在内部执行网络调用 onHandleIntent()上 -那么它确实会在工作线程上运行。希望这能有所帮助。