3

我使用BroadcastReceiver,IntentService作爲後臺操作並將數據傳遞給Activity。據我所知,IntentService在不同UI線程執行,不過我有android.os.NetworkOnMainThreadExceptionandroid.os.NetworkOnMainThreadException IntentService的onHandleIntent方法

的方法來註冊的廣播接收器:

private void registerReceiver() 
{ 
    // создаем BroadcastReceiver 
    bCarBroadcast = new BroadcastReceiver() { 
     // действия при получении сообщений 
     public void onReceive(Context context, Intent intent) { 
      int status = intent.getIntExtra(Constants.CAR_SEARCH_STATUS, 0); 
      int task = intent.getIntExtra(Constants.CAR_SEARCH_TASK, 0); 
      Log.d(TAG, "onReceive: task = " + task + ", status = " + status); 

      if (status == Constants.STATUS_RUNNING) { 
         beginProgressTask(); 
      } 

      if (status == Constants.STATUS_FINISHED) { 
       String data = intent.getStringExtra(Constants.CAR_SEARCH_DATA); 
        if(data!=null) 
         car_search_result_str.setText(data); 

      } 
     } 
    }; 
    IntentFilter intFilt = new IntentFilter(Constants.BROADCAST_ACTION); 
    registerReceiver(bCarBroadcast, intFilt); 
} 

的onCreate:

 @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.car_search_activity); 
     registerReceiver(); 
      Intent a= new Intent(this, OrderStateService.class); 
      startService(a); 
    } 

IntentService

public class OrderStateService extends IntentService { 
    private static final String TAG = "OrderStateService"; 
    private JSONObject jsonResponse; 

    public OrderStateService() { 
     super("OrderStateService"); 
    } 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     onHandleIntent(intent); 
     return START_REDELIVER_INTENT; 
    } 
    @Override 
    public void onStart(Intent intent, int startId) { 
     onHandleIntent(intent); 
    } 
    @Override 
    protected void onHandleIntent(Intent intent) { 

     Intent intentResult = new Intent(Constants.BROADCAST_ACTION); 
     intent.putExtra(Constants.CAR_SEARCH_STATUS, Constants.STATUS_RUNNING); 
     sendBroadcast(intentResult); 
     final Bundle data = new Bundle(); 

     DefaultHttpClient httpclient = new DefaultHttpClient(); 
     String url = Constants.HOST_URL + "/api/version/";//Constants.ORDER_URL + intent.getStringExtra(Constants.ORDER_ID); 
     Log.i(TAG, url); 

     HttpGet httpget = new HttpGet(url); 
     // Some try and catch that I am leaving out 
     try { 
      httpget.addHeader("Authorization", SharedPrefsSingleton.getInstance().getSharedPrefs().getString(Constants.USER_AUTHORIZATION, null)); 
      httpget.addHeader("Content-Type", "application/json"); 
      httpget.addHeader("Accept", "application/json; charset=utf-8"); 
      httpclient.execute(httpget); 

      HttpResponse response = (HttpResponse) httpclient.execute(httpget); 
      ; 

      Log.i(TAG + " code", Integer.toString(response.getStatusLine().getStatusCode())); 
      HttpEntity entity = response.getEntity(); 

      if (entity != null) { 
       // Read the content stream 
       InputStream instream = entity.getContent(); 
       Header contentEncoding = response.getFirstHeader("Content-Encoding"); 
       if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
        instream = new GZIPInputStream(instream); 
       } 
       // convert content stream to a String 
       String resultString = Utils.getStringFromInputStream(instream); 
       instream.close(); 
       response.getEntity().consumeContent(); 
       // Transform the String into a JSONObject 
       jsonResponse = new JSONObject(resultString); 
       Log.i(TAG, jsonResponse.toString()); 
       if (jsonResponse.has("order_car_info")) 
       { 
        data.putString(Constants.RECEIVER_DATA, "Error"); 
       } 
       else 
       { 
        data.putString(Constants.RECEIVER_DATA, jsonResponse.toString()); 
        intent.putExtra(Constants.CAR_SEARCH_STATUS, Constants.STATUS_FINISHED); 
        intent.putExtra(Constants.CAR_SEARCH_DATA, jsonResponse.toString()); 
        sendBroadcast(intent); 
       } 



      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 

回溯:

android.os.NetworkOnMainThreadException 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:112) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at java.net.Socket.connect(Socket.java:843) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at library.OrderStateService.onHandleIntent(OrderStateService.java:59) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at library.OrderStateService.onStartCommand(OrderStateService.java:31) 
12-06 03:00:02.888 22280-22280/codenest.testaplication W/System.err﹕ at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2702) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at android.app.ActivityThread.access$2100(ActivityThread.java:135) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at android.os.Looper.loop(Looper.java:136) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
12-06 03:00:02.898 22280-22280/codenest.testaplication W/System.err﹕ at dalvik.system.NativeStart.main(Native Method) 
+1

你執行它不應該自己調用'onHandleIntent()'。另外,我不相信你需要重寫'onStart()'或'onStartCommand()'。 – 2014-12-06 01:22:33

+0

謝謝,問題解決了 – 2014-12-06 01:26:05

回答

0

刪除代碼的

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    onHandleIntent(intent); 
    return START_REDELIVER_INTENT; 
} 
@Override 
public void onStart(Intent intent, int startId) { 
    onHandleIntent(intent); 
} 

部分解決了我的問題。

由於Mike

0

創建一個單獨的AsyncTask和移動

DefaultHttpClient httpclient = new DefaultHttpClient(); 
    String url = Constants.HOST_URL + "/api/version/";//Constants.ORDER_URL + intent.getStringExtra(Constants.ORDER_ID); 
    Log.i(TAG, url); 

    HttpGet httpget = new HttpGet(url); 
    // Some try and catch that I am leaving out 
    try { 
     httpget.addHeader("Authorization", SharedPrefsSingleton.getInstance().getSharedPrefs().getString(Constants.USER_AUTHORIZATION, null)); 
     httpget.addHeader("Content-Type", "application/json"); 
     httpget.addHeader("Accept", "application/json; charset=utf-8"); 
     httpclient.execute(httpget); 

     HttpResponse response = (HttpResponse) httpclient.execute(httpget); 
     ; 

     Log.i(TAG + " code", Integer.toString(response.getStatusLine().getStatusCode())); 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
      // Read the content stream 
      InputStream instream = entity.getContent(); 
      Header contentEncoding = response.getFirstHeader("Content-Encoding"); 
      if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
       instream = new GZIPInputStream(instream); 
      } 
      // convert content stream to a String 
      String resultString = Utils.getStringFromInputStream(instream); 
      instream.close(); 
      response.getEntity().consumeContent(); 
      // Transform the String into a JSONObject 
      jsonResponse = new JSONObject(resultString); 
      Log.i(TAG, jsonResponse.toString()); 
      if (jsonResponse.has("order_car_info")) 
      { 
       data.putString(Constants.RECEIVER_DATA, "Error"); 
      } 
      else 
      { 
       data.putString(Constants.RECEIVER_DATA, jsonResponse.toString()); 
       intent.putExtra(Constants.CAR_SEARCH_STATUS, Constants.STATUS_FINISHED); 
       intent.putExtra(Constants.CAR_SEARCH_DATA, jsonResponse.toString()); 
       sendBroadcast(intent); 
      } 



     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

這些代碼到它

doInBackground方法創建異步任務,並在您的onHandleIntent

相關問題