Android.os.NetworkOnMainThreadException in onHandleIntent method of IntentService

I am using BroadcastReceiver

, IntentService

for background operations and passing data to Activity

. As I know, it IntentService

is executed as opposed to a thread UI

, nevertheless I haveandroid.os.NetworkOnMainThreadException

BroadcastReceiver registration method:

  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);
    }

      

and 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();
        }
    }

}

      

back trace:

    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)

      

+3


source to share


2 answers


Deleting

 @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);
}

      



some of the code solved my problem.

Thanks Mike

0


source


Create a separate AsyncTask and move

    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();
    }

      



this code into the doInBackground method from it

Create an async task and execute it in onHandleIntent

0


source







All Articles