2

问题

我正在运行其中的方法HttpsUrlConnection.getInputStream(),该方法AsyncTask.doInBackground()DialogFragment.

我希望它在用户退出片段时终止。

如果我不这样做,无用的数据将继续在后台加载。

我试过的

我尝试在回调中将URLConnection对象设置为 ,但它不会阻止该方法执行。我无法在 UI 线程中调用,并且在另一个 AsyncTask 中将无效,因为它们是按顺序执行的。nullonDismiss()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()在我的函数中几乎没有时间。

4

1 回答 1

0

您可以从 UI 调用AsyncTask.cancel(true);并在其中doInBackground()继续调用isCancelled()以检测函数是否必须中止,之后您可以做任何您需要的事情

我们可以在这里阅读

取消任务 可以随时通过调用 cancel(boolean) 取消任务。调用此方法将导致对 isCancelled() 的后续调用返回 true。[...] 为确保尽快取消任务,如果可能(例如在循环内),您应该始终从 doInBackground(Object[]) 定期检查 isCancelled() 的返回值。

在你的 doInBackground你有功能 convertStreamToString功能。这是最长的操作,在里面你肯定可以中断下载。对于其中的 usre,您可以使用任何类型的循环来检索流的内容并将其保存到字符串中,并且可以在其中中止它。

 private void convertStreamToString () {    


            //..


           //loop to convert StreamToString
           {
               //..

              // Escape early if cancel() is called
             if (isCancelled()) {
                 mConnection.disconnect()
                 break;
             }
           }

   }
于 2014-02-03T17:34:35.760 回答