问题
我正在运行其中的方法HttpsUrlConnection.getInputStream()
,该方法AsyncTask.doInBackground()
从DialogFragment
.
我希望它在用户退出片段时终止。
如果我不这样做,无用的数据将继续在后台加载。
我试过的
我尝试在回调中将URLConnection
对象设置为 ,但它不会阻止该方法执行。我无法在 UI 线程中调用,并且在另一个 AsyncTask 中将无效,因为它们是按顺序执行的。null
onDismiss()
getInputStream()
mConnection.disconnect()
AsyncTask.cancel()
没有用,因为它不会停止该doInBackground()
方法。
问题
如何强制从 getInputStream() 方法返回?
代码
根据@CarlosRobles 的要求,这是我的 doInBackground() 的代码
URL url = new URL(urlString);
setCurrentConnection((HttpsURLConnection) url.openConnection());
mCurrentConnection.setSSLSocketFactory(mSSLSocketFactory);
mCurrentConnection.connect();
int responseCode = mCurrentConnection.getResponseCode();
if (responseCode >= 400) {
throw new IOException("Bad response code");
}
Log.d(TAG, "response code: " + responseCode);
// TODO: Should call .close() if IOException happens here?
InputStream inputStream = mCurrentConnection.getInputStream();
String response = convertStreamToString(inputStream);
inputStream.close();
mCurrentConnection.disconnect();
return response;
其他注意事项
我刚刚检查了上面代码片段中调用的所有函数的执行时间,我发现UrlConnection.getResponseCode()
, 是迄今为止运行时间最长的函数。我想这是由于对它UrlConnection.getInputStream()
内部的调用。后来,inputStream 总是被缓存到连接对象中,这就是为什么UrlConnection.getInputstream()
在我的函数中几乎没有时间。