我需要取消我的 asyncthread 。在我的应用程序中,我正在做一些繁重的计算,我想让用户能够取消计算(然后重试)。我在论坛上读到,您不能只是停止任务正在执行的操作,并且您需要检查任务 isCancelled=true 在您的 DoinBackground 代码中是否存在。但这对我不起作用。
任务本身运行良好,如果我让它自行结束,它会输出正确的数据。
在我的应用程序中,我首先调用函数 naredi_pdf_start(view),然后当任务运行时,如果我调用 close_pdf1(view),它会给我一个错误。(我正在更改视图并且应用程序在调用 publishProgress 时找不到我的 pdf_text1 Textview - 空指针异常)。我真的不知道如何使用 task.cancel(true) 方法(在我的例子中:start_pdf.cancel(true)))。
这是我的代码:
String progress_pdf;
naredi_pdf start_pdf;
public void naredi_pdf_start(View view) {
    start_pdf=new naredi_pdf();
    start_pdf.execute();
}
public void close_pdf1(View view) {
    if(start_pdf!=null) {
        Log.v("not null","not null");
        start_pdf.cancel(true);
        setContentView(R.layout.other_view); //This is where 
                                             //I don't have TextView pdf_text1
    }
}
private class naredi_pdf extends AsyncTask<Void, String, Void> {
    protected Void doInBackground( Void... ignoredParams ) {
        progress_pdf="Calculating Statistical Data";
        //A LOT OF CODING
        for(int i = 0; i < 1; i++) {
            if(isCancelled()) {
                break;
            }
            else {
                publishProgress("Calculating team statistics");  
            }
        }
        //MORE OF CODING              
        for (int i = 0; i < 1; i++) {
            if (isCancelled()) {
                break;
            }
            else {
                publishProgress("Calculating player's BIO");  
            }
        }
        //MORE OF CODING       
        for (int i = 0; i < 1; i++) {
            if (isCancelled()) {
                break;
            }
        else {
                publishProgress("Calculating player's individual performance");
            }
        }
        return null; 
    }
    protected void onPostExecute( Void array ) {
        //saving to database
    }
    protected void onProgressUpdate(String... values) {
        progress_pdf=values[0]+"\n"+progress_pdf;
        if (isCancelled())  {
        }
        else {
            TextView pdf_text1 = (TextView) findViewById (R.id.pdf_text1);
            pdf_text1.setText(progress_pdf);
            // dialog(view);
        }
    }
}