我有以下代码:
// Activate every time UART Characteristic is updated
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
final String[] data = new String(characteristic.getValue()).split("/");
String endpoint = "http://192.168.1.100:8000/rest/store/"+gatt.getDevice().getAddress()+"/"+data[0]+"/"+data[1]+"/"+data[2]+"/"+Long.toString(System.currentTimeMillis());
try { new uploadData().execute(new URL(endpoint)); }
catch (MalformedURLException e) { e.printStackTrace(); }
String endpoint2 = "http://192.168.1.100:8000/rest/status/"+gatt.getDevice().getAddress();
try { new checkServer().execute(new URL(endpoint2)); }
catch (MalformedURLException e) { e.printStackTrace(); }
}
每次加速计更新其值时,我都会收到一条激活onCharacteristicChanged
的通知。
uploadData
,是一个异步任务,尝试将加速计信息上传到我的服务器。它没有超时,因为它必须等到服务器在线才能丢失信息。
checkServer
是一个异步任务,用于检查服务器运行状况,并在android上显示消息(如果它在线)。它有500毫秒的超时时间,表明服务器处于脱机状态。
以下是代码:
private class uploadData extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
urlConnection.getResponseMessage();
urlConnection.disconnect();
}
catch (IOException e) { }
return null;
}
}
private class checkServer extends AsyncTask<URL, Integer, String> {
String result;
protected String doInBackground(URL... urls) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
urlConnection.setConnectTimeout(500);
result = urlConnection.getResponseMessage();
urlConnection.disconnect();
}
catch (IOException e) { result = "404"; }
return result;
}
protected void onPostExecute(String result) {
if (result.equalsIgnoreCase("OK")) {
((TextView) findViewById(R.id.http)).setText("Sending data");
((TextView) findViewById(R.id.http)).setTextColor(Color.GREEN);
}
else{
((TextView) findViewById(R.id.http)).setText("Server offline");
((TextView) findViewById(R.id.http)).setTextColor(Color.RED);
}
}
}
当服务器在线时,一切正常。它发送信息并显示服务器在线。
但是当服务器处于脱机状态时,它会卡在消息中:Sending data
。
为什么会卡住?似乎他等到uploadData完成,但它没有超时,所以它永远不会执行,直到服务器再次联机。 Android不会同时执行所有http请求吗?
答案 0 :(得分:0)
尝试在onPostExecute方法上添加一个语句:
if (result == "404")`{add a dispplay msg here}`