IntentService的onHandleIntent方法中的android.os.NetworkOnMainThreadException

时间:2014-12-06 01:14:38

标签: android android-activity broadcastreceiver intentservice

我正在使用BroadcastReceiverIntentService进行后台操作,并将数据传递给Activity。据我所知,IntentService正在执行与UI线程不同,但我已经android.os.NetworkOnMainThreadException

注册BroadcastReceiver的方法:

  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)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

中执行