2013-02-18 42 views
1

我有確實網絡動作(HTTP POST)的IntentService,但它示出了NetworkOnMainThreadException。如果我是對的,IntentService將在單獨的線程上運行。任何人都可以告訴爲什麼拋出這個異常?我的代碼是:NetworkOnMainThreadException在IntetentService

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; 

} 
    } 
+0

你是不是想在Android 3.0或更高版本的代碼? – Bigflow 2013-02-18 11:39:29

+0

@Bigflow。是的..我寫在ICS ..我想你也會得到這樣的例外只有在3.0以上.. – nidhin 2013-02-19 05:29:27

+0

是的,這是正確的,看看sajmon_d的答案。 – Bigflow 2013-02-19 07:10:14

回答

1

給出的問題是,你沒有運行的網絡請求onHandleIntent(),你只是創造BroadcastReceiver實例和註冊它。實際的網絡請求將不會在那裏運行。當BroadcastReceiver收到一條消息,這發生在UI線程它將會運行。這裏的一個正確的方案是創建你的BroadcastReceiver別處,而在收到消息時,啓動IntentService,這裏面執行一個onHandleIntent()網絡呼叫 - 那麼它的確將在一個工作線程運行。希望這可以幫助。

+0

Thaks @Egor ..有幫助。但我有一個活動在主線程中運行,我希望此服務始終在後臺運行,以監視網絡狀態。那麼是否有可能在另一個服務中創建'BroadcastReceiver'並調用'IntentService'?或者有沒有其他的方式來監控網絡狀態而不使用主線程? – nidhin 2013-02-19 05:08:11

+0

@nidhin,這裏有監控連接狀態一個很好的參考: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html 如你所見,你需要一個BroadcastReceiver來監控連接。 – Egor 2013-02-19 07:43:54

相關問題