Java 如果需要的时间太长,请重新启动操作

Java 如果需要的时间太长,请重新启动操作,java,android,android-asynctask,Java,Android,Android Asynctask,我有一个从第三方网站下载信息的异步任务。这个网站不在我的控制之下 问题是,有时我会在2秒内得到这些信息,但有时可能需要30-40秒 我知道问题出在网站本身,因为我在我的桌面上的网络浏览器中遇到了同样的问题 我要寻找的是一种方法,如果需要的时间超过一定数量,可以取消该操作,然后重试 这是我目前的代码: protected ArrayList<Card> doInBackground(Void... voids) { Looper.prepare(); publishPr

我有一个从第三方网站下载信息的异步任务。这个网站不在我的控制之下

问题是,有时我会在2秒内得到这些信息,但有时可能需要30-40秒

我知道问题出在网站本身,因为我在我的桌面上的网络浏览器中遇到了同样的问题

我要寻找的是一种方法,如果需要的时间超过一定数量,可以取消该操作,然后重试

这是我目前的代码:

protected ArrayList<Card> doInBackground(Void... voids)
{
    Looper.prepare();
    publishProgress("Preparing");
    SomeClass someClass = new SomeClass(this);

    return someClass.downloadInformation();
}
protectedarraylist doInBackground(Void…voids)
{
Looper.prepare();
出版进度(“准备”);
SomeClass SomeClass=新的SomeClass(此);
返回someClass.downloadInformation();
}

您可以尝试为Http请求设置超时和套接字连接。您可以看到以下链接: 知道如何设置它们

并使用HttpRequestRetryHandler启用自定义异常恢复机制

From:“默认情况下,HttpClient尝试从I/O异常中自动恢复。默认自动恢复机制仅限于少数已知安全的异常

  • HttpClient不会尝试从任何逻辑或HTTP协议错误(从HttpException类派生的错误)中恢复
  • HttpClient将自动重试那些假定为幂等的方法
  • 当HTTP请求仍在传输到目标服务器时(即,请求尚未完全传输到服务器),HttpClient将自动重试那些因传输异常而失败的方法。”
例如:

DefaultHttpClient httpclient = new DefaultHttpClient();

HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

public boolean retryRequest(
        IOException exception, 
        int executionCount,
        HttpContext context) {
    if (executionCount >= 5) {
        // Do not retry if over max retry count
        return false;
    }
    if (exception instanceof InterruptedIOException) {
        // Timeout
        return false;
    }
    if (exception instanceof UnknownHostException) {
        // Unknown host
        return false;
    }

    if (exception instanceof SocketTimeoutException) {
        //return true to retry 
        return true;
    }

    if (exception instanceof ConnectException) {
        // Connection refused
        return false;
    }
    if (exception instanceof SSLException) {
        // SSL handshake exception
        return false;
    }
    HttpRequest request = (HttpRequest) context.getAttribute(
            ExecutionContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); 
    if (idempotent) {
        // Retry if the request is considered idempotent 
        return true;
    }
    return false;
}

};

httpclient.setHttpRequestRetryHandler(myRetryHandler);
请参阅此链接:
了解更多详情。

非常感谢。真是太棒了。我一拿到电脑就去测试:)这个答案很完美。非常感谢你