现在的位置: 首页 > 综合 > 正文

如何停止正在运行的AsyncTask

2018年02月10日 ⁄ 综合 ⁄ 共 755字 ⁄ 字号 评论关闭
<code><span class="pln"><span style="font-size:12px;"><span style="font-family: arial, helvetica, sans-serif;">public class MyTask extends AsyncTask<Void, Void, Void> {



    private volatile boolean running = true;

    private final ProgressDialog progressDialog;



    public MyTask(Context ctx) {

        progressDialog = gimmeOne(ctx);



        progressDialog.setCancelable(true);

        progressDialog.setOnCancelListener(new OnCancelListener() {

            @Override

            public void onCancel(DialogInterface dialog) {

                // actually could set running = false; right here, but I'll

                // stick to contract.

                cancel(true);

            }

        });



    }



    @Override

    protected void onPreExecute() {

        progressDialog.show();

    }



    @Override

    protected void onCancelled() {

        running = false;

    }



    @Override

    protected Void doInBackground(Void... params) {



        while (running) {

            // does the hard work

        }

        return null;

    }



    // ...



}</span></span></span></code>

抱歉!评论已关闭.