android - Android执行不同的http请求卡住
问题描述
我有以下代码:
// 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请求吗?
解决方案
尝试在 onPostExecute 方法上添加一条语句:
if (result == "404")`{add a dispplay msg here}`
推荐阅读
- css - 如何设置基于flex或grid的动态网格
- excel - Excel Solver 排除价格为零的地方
- emacs - 有没有办法根据子标题 todo-keywords 计算 org-mode 标题属性?
- windows - 从 powershell 输出中删除文本
- node.js - 使用 NodeJS Bull Queue 独立处理器
- javascript - 用文本替换损坏的图像
- javascript - 如何在 Blazor 客户端中正确获取 facebook 登录令牌?
- html - 如何根据时间戳和电子表格上的文本在图表上添加文本标签
- python - 将 Pandas 索引设置为给定的 DateTimeindex
- .net - 使用 VBA 从 Access 应用程序中使用 ASP.NET Web 服务