【问题标题】:AsyncTask is not cancelling the long running operation in androidAsyncTask 没有取消 android 中长时间运行的操作
【发布时间】:2013-01-21 09:21:12
【问题描述】:

我必须从服务器下载大量数据。下载至少需要 10 秒。这是我使用 asyntask 类下载的代码。如果用户在下载操作进行时单击主页按钮,我想无条件取消下载操作。问题是......我正在执行 cancel() 方法,但它没有取消下载操作。即使我退出应用程序,我也看到该操作在 logcat 视图中在后台运行。我只想停止执行 doInBackground() 方法。请指导/帮助我。

点击下载按钮:

  dwnldTask = new DownloadTask ();
  dwnldTask.execute(SERVER_URL);

这里是 Asynctask 类:

 class DownloadTask extends AsyncTask<String, Void, Object>{
    private Object response = null;

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

         displaying progress dialog on UI 
    }
    @Override
    protected Object doInBackground(String... params) {
        try{   

             DataConnection dc = new DataConnection();

             this.response = dc.connectToServer(params[0]);

            if(isCancelled()){
                return null;
            }


        }catch (Exception e) {
            if(isCancelled()){
                return null;
            }   
            e.printStackTrace();
            showToastMSG(e.getMessage());
        }  

        return this.response ;
    }

    @Override
    protected void onPostExecute(Object response) {
        super.onPostExecute(response);

        if(response != null ){ 
            successfully downloaded...  go to next activity
             } 
            cancel progress dialog here
    }

} 

在 onPause() 里面..

  @Override
protected void onPause() {
    super.onPause();
    if(dwnldTask != null && dwnldTask.getStatus() == AsyncTask.Status.RUNNING){
        dwnldTask.cancel(true);
    }  
     cancel the progress dialog if it is showing

}

这是位于另一个名为 DataConnection 的类中的方法...

  public Object connectToServer(String url) throws Exception{
    HttpGet request = new HttpGet(url);
    request.addHeader("accept","application/json");
    HttpResponse response = httpClient.execute(request);   
    HttpEntity httpEntity = response.getEntity();
    InputStream responseInputStream = httpEntity.getContent();
    return myUtilObject.convertInputStreamToString(responseInputStream);
}

【问题讨论】:

  • 你可以打断它。在网络调用过程中你会得到一个中断的异常
  • 按下主页按钮时不会调用onStop()
  • 您确定将dwnldTask 设置为任务对象吗?你确定你打电话给onStop()

标签: android android-asynctask cancellation


【解决方案1】:

我同意 Ran - 你没有编写以下代码: myUtilObject.convertInputStreamToString 但我猜你在输入流上循环使用你预定义其大小的缓冲区(也许使用 BufferedReader?) - 在这个循环中,你应该检查异步线程的停止条件 - isCancelled() 是一个很好的例子。

如果线程被取消,循环应该停止,即:

String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024);
while ((line = rd.readLine()) != null && !isCancelled())
{
     total.append(line);
}

【讨论】:

  • 已解决。谢谢你们俩。
【解决方案2】:

你在执行下载后检查isCancelled()方法,所以它没有理由在中间被取消。

通常你会这样做:

while (!isCancelled()) {
 // Download next buffer..
}

在这种情况下,一旦发出取消请求,循环就会停止。

【讨论】:

  • 有一个原因 - 他正在调用cancel(true),其中true 表示应该使用InterruptedException 中断IO 操作。
  • @Ran :我有一个单独的类,其中我有连接服务器并从服务器读取数据的方法。因此,我正在为该类创建一个对象并调用从 doInBackground() 下载的方法。我如何检查该类中的操作是否被取消?
猜你喜欢
  • 1970-01-01
  • 2012-09-29
  • 2021-10-29
  • 2012-04-03
  • 1970-01-01
  • 2016-02-22
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多