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
}
有谁能帮我解决这个问题吗?

Thanks in advance

问题来了。您正在尝试使用第二个实例来取消第一个实例:

    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(); 
}

相关内容

  • 没有找到相关文章

最新更新