AsyncTask的是不是取消android系统的长时间运行操作 [英] AsyncTask is not cancelling the long running operation in android

查看:103
本文介绍了AsyncTask的是不是取消android系统的长时间运行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从服务器上下载大量的数据。它正在采取最小10秒至下载。这里是我的code。使用asyntask类下载。我要无条件地取消下载操作,如果用户点击Home键,同时下载操作是怎么回事。问题是...我'执行取消()方法,但它不取消下载操作。我'看到,操作是在logcat中查看后台运行,即使我出来的应用。我只是想阻止doInBackground()方法的执行。请指导/帮助我。

在下载按钮中点击:

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

和这里的AsyncTask类:

 类DownloadTask扩展的AsyncTask<弦乐,太虚,对象> {
    私有对象响应= NULL;    @覆盖
    在preExecute保护无效(){
        super.on preExecute();         显示进度对话框上的UI
    }
    @覆盖
    保护对象doInBackground(字符串... PARAMS){
        尝试{             DataConnection直流=新DataConnection();             this.response = dc.connectToServer(PARAMS [0]);            如果(isCancelled()){
                返回null;
            }
        }赶上(例外五){
            如果(isCancelled()){
                返回null;
            }
            e.printStackTrace();
            showToastMSG(e.getMessage());
        }        返回this.response;
    }    @覆盖
    保护无效onPostExecute(对象响应){
        super.onPostExecute(响应);        如果(响应!= NULL){
            成功下载...去到下一个活动
             }
            取消进度对话框这里
    }}

里面的onPause()。

  @覆盖
保护无效的onPause(){
    super.onPause();
    如果(dwnldTask = NULL&放大器;!&安培; dwnldTask.getStatus()== AsyncTask.Status.RUNNING){
        dwnldTask.cancel(真);
    }
     取消进度对话框,如果它显示}

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

 公共对象connectToServer(字符串URL)抛出异常{
    HTTPGET请求=新HTTPGET(URL);
    request.addHeader(接受,应用/ JSON);
    HTT presponse响应= httpClient.execute(请求);
    HttpEntity httpEntity = response.getEntity();
    InputStream的responseInputStream = httpEntity.getContent();
    返回myUtilObject.convertInputStreamToString(responseInputStream);
}


解决方案

我同意冉 - 你没有写的code:
myUtilObject.convertInputStreamToString
但即时通讯有猜你遍历一个缓冲的InputStream你predefined它的大小(可能与BufferedReader类?) - 在这个循环中,你应该检查你的异步线程的停止条件 - isCancelled()是一个很好的例子。

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

 串线=;
StringBuilder的总=新的StringBuilder();
RD的BufferedReader =新的BufferedReader(新的InputStreamReader(是),1024);
而((行= rd.readLine())= NULL和放大器;!&安培;!isCancelled())
{
     total.append(线);
}

I have to download huge amount of data from server. It is taking minimum 10 seconds to download. Here is my code to download using asyntask class. And I want to cancel the downloading operation unconditionally if the user clicks on home button while downloading operation is going on. The problem is... I'am executing cancel() method but it is not cancelling the downloading operation. I'am seeing that operation is running in background in logcat view even i came out of application. I just want to stop the execution of doInBackground() method. Please guide/help me.

on click of download button :

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

And here is Asynctask class :

 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
    }

} 

Inside 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

}

Here is the method located in another class named 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);
}

解决方案

I agree with Ran - you didn't write the code of: myUtilObject.convertInputStreamToString but im guessing you loop there over the inputstream with a buffer you predefined its size (maybe with BufferedReader?) - in this loop you should check the stop condition of your async thread - isCancelled() is a good example.

The loop should stop if the thread is canceled, i.e.:

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

这篇关于AsyncTask的是不是取消android系统的长时间运行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆