Android - 无法取消AsyncTask

时间:2015-05-23 07:11:11

标签: android android-asynctask

我每30秒生成30000个值,并且使用AsyncTask绘制带有该值的图表。问题是如果第二组值到来我需要取消运行AsyncTask,我需要用AsyncTask绘制第二组值。但我无法取消AsyncTask

以下是代码段

CountDownTimer ct;
DrawGraphAsync dga;

// onCreate
ct=new CountDownTimer(30*1000, 1000) {
    public void onTick(long millisUntilFinished) {

    }

    public void onFinish() {
        dga= new DrawGraphAsync();

        if(dga.getStatus()==AsyncTask.Status.RUNNING){
            Log.d("TAG",MainActivity.this.dga.getStatus().toString());
            dga.cancel(true);
        }           
        dga.execute();
        ct.start(); 
    }
}.start();

// InAsyncTask   

@Override
    protected String doInBackground(String... params) {
        Log.d("TAG","DOINBACK GROUND TASK:: ");
    try{                
            for(int cout=0;cout<30000;cout++){

                if(isCancelled()){
                    Log.d("TAG","CANCELLED DOINBACK:: ");
                    break;
                }
                // Code to paint the graph
            }                          
                }catch(Exception e){                        
                    e.printStackTrace();
                }

    return null
}

有谁可以帮我解决这个问题?

提前致谢

1 个答案:

答案 0 :(得分:1)

这是问题所在。您正尝试使用第二个实例取消第一个实例:

    dga= new DrawGraphAsync();

    if(dga.getStatus()==AsyncTask.Status.RUNNING){
        Log.d("TAG",MainActivity.this.dga.getStatus().toString());

        // this will cancel the task you just allocated that has yet to start.
        // And it leaks the previous task that was allocated
        dga.cancel(true); 

    }           
    dga.execute();

将onFinish代码更改为:

public void onFinish() {

    if (dga != null) && (dga.getStatus()==AsyncTask.Status.RUNNING) {
        dga.cancel(true);
        dga = null;
    }           

    dga= new DrawGraphAsync();
    dga.execute();
    ct.start(); 
}