gpt4 book ai didi

java - 当用户按下后退时取消正在进行的连接

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:48 26 4
gpt4 key购买 nike

我一直在搜索这个,但没有找到我的具体问题。我知道 AskyncTask 可以使用 .cancel(true) 取消,但这只有在我有一个可以检查值的循环时才会发生 isCanceled()

但我的问题是..当用户按回键时,我如何取消 AsyncTask(卡在 httpclient.execute() 中)?如果用户离开该 Activity 并转到另一个我不想运行不受控制的 AsyncTask 数量,因为这可能会导致内存问题,用户可以来回导航并创建不确定数量的任务。这就是为什么我想关闭它们。有人知道办法吗?我发布了用于连接的代码:

public class Test extends Activity {

@Override
protected void onStart() {
super.onStart();

new ConnectionTask().execute("https://www.mywebserver.com/webservice.php?param1=test");
}

private class ConnectionTask extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... params) {
try {

HttpClient httpclient = DefaultHttpClient(params,clientConnectionManager);
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

if(httpEntity != null)
return EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

}

}

你知道我应该在 onStop() 中添加什么来取消正在进行的 httpClient.execute() 功能吗?有时几乎永远卡住。

非常感谢您的帮助,在此先感谢您。

更新

如果我关闭 ConnectionManager,我必须再次为 https 进行握手,对吗?在我创建 httpClient 时查看这段代码,我将其用于 https:

HttpClient httpclient = DefaultHttpClient(params,clientConnectionManager);

感谢大家的快速回复以及此处公开的各种解决方案。我将尝试使用超时(不必等待太多)+ cancel() 函数来避免处理 onPostExecute。我会告诉你结果是否符合预期!非常感谢大家!

最佳答案

根据 HttpClient docs , 使用 HttpUriRequest#abort() 中止请求

1.4. Aborting requests

In some situations HTTP request execution fails to complete within the expected time frame due to high load on the target server or too many concurrent requests issued on the client side. In such cases it may be necessary to terminate the request prematurely and unblock the execution thread blocked in a I/O operation. HTTP requests being executed by HttpClient can be aborted at any stage of execution by invoking HttpUriRequest#abort() method. This method is thread-safe and can be called from any thread. When an HTTP request is aborted its execution thread - even if currently blocked in an I/O operation - is guaranteed to unblock by throwing a InterruptedIOException

关于java - 当用户按下后退时取消正在进行的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7391250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com