首页 > 解决方案 > 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请求吗?

标签: androidhttpasynchronous

解决方案


尝试在 onPostExecute 方法上添加一条语句:

if (result == "404")`{add a dispplay msg here}`

推荐阅读