Async HTTP Request and Arduino

1.3k views Asked by At

I am developing an Android Application that will communicate with an Arduino Uno though Wifi. The arduino is already programmed to turn on the digital port number 12 when I access the address 192.168.11.110. When I open my browner and I access the address the red LED (connected to the port 12) turns on, when I access again it turns off, works perfectly. The problem is in the Android app that I make a HTTP Request, the LED turns on and it seems that the connection is "stucked", I can't turn off the led and I can't access through a browser unless I restart the Arduino or I end the Android Activity.

The piece of code that I use to make a HTTP request in the Android app is this:

public class ArduinoRequest extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            out.close();
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        //TODO Handle problems..
    }
    return responseString;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    }
}

Then in my

MenuActivity.java

I call this

ArduinoRequest arduinoRequest = new ArduinoRequest();
                  arduinoRequest.execute("http://192.168.11.110");

Any idea? :)

EDIT:

I just solved. Use this code instead:

   // Instantiate the RequestQueue.
              RequestQueue queue = Volley.newRequestQueue(MenuActivity.this);
              String url ="http://192.168.11.110/";

            // Request a string response from the provided URL.
              StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                      new Response.Listener<String>() {
                          @Override
                          public void onResponse(String response) {
                              // Display the first 500 characters of the response string.
                             // mTextView.setText("Response is: "+ response.substring(0,500));
                          }
                      }, new Response.ErrorListener() {
                  @Override
                  public void onErrorResponse(VolleyError volleyError) {

                  }

              });
0

There are 0 answers