我正在开发一个Android应用程序,它将通过Wifi与Arduino Uno进行通信。当我访问地址192.168.11.110时,arduino已被编程为打开数字端口号12。当我打开我的浏览器并访问地址时,红色LED(连接到端口12)打开,当我再次访问它关闭时,工作完美。问题出在Android应用程序中,我发出了HTTP请求,LED亮起,看起来连接已经过了#",我无法关闭LED,我可以'通过浏览器访问,除非我重新启动Arduino或结束Android活动。
我在Android应用中用来发出HTTP请求的代码是:
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);
}
}
然后在我的
MenuActivity.java
我称之为
ArduinoRequest arduinoRequest = new ArduinoRequest();
arduinoRequest.execute("http://192.168.11.110");
有什么想法吗? :)
编辑:
我刚刚解决了。请改用此代码:
// 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) {
}
});