在Android中停止AsyncTask

时间:2018-04-06 23:30:13

标签: android android-asynctask

我正在尝试停止Android中的AsyncTask。在doInBackground中,它运行一个IP地址列表并尝试ping所有这些。

此外,执行AsyncTask时会打开ProgressDialog,您可以取消它。调用此取消 - 文本调用AsyncTask中的onCancelled方法。因此,正在调用此方法,但似乎它永远不会停止,因为当我再次按下按钮时,我总是收到以下错误消息:

java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)

这是我的代码:

private Settings.HostWorker hostWorker;

private void initComponents() {
    hostWorker = new Settings.HostWorker();
    progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
        if(!hostWorker.isCancelled()) {
            hostWorker.cancel(true);
        }
    }
});
}

findServerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v)
    {
        if(findServerButton.isClickable()) {
            progressDialog.show();
            hostWorker.execute();
            findServerButton.setClickable(false);
        }
    }
});

private class HostWorker extends AsyncTask<Integer, String, Void> {
    @Override
    protected Void doInBackground(Integer... params) {
        try {
            for (int i = 0; i <= 255; i++) {
                String ip = createHostsList(i);
                if (ip != null) {
                    publishProgress(ip);
                }
                if(isCancelled())
                {
                    break;
                }
            }
        } catch (Exception e) {
    MyAlertDialog myAlertDialog = new MyAlertDialog(getBaseContext(),     "Error in Settings - doInBackground: " + e.getMessage());
    myAlertDialog.showAlertDialog();
    }
    return null;
}
protected void onProgressUpdate(String... values) {
    hostsOnline.add(values[0]);
    settingsCustomArrayAdapter.notifyDataSetChanged();
}

protected void onCancelled(){
    findServerButton.setClickable(true);
}

@Override
protected void onPostExecute(Void aVoid)
{
    super.onPostExecute(aVoid);
}
}

1 个答案:

答案 0 :(得分:1)

错误

  

无法执行任务:任务已执行(任务只能执行一次)

建议您每次要运行任务时都需要创建一个新的HostWorker实例。您可以通过删除行

来实现此目的
hostWorker = new Settings.HostWorker();

来自initComponents,然后将其添加到findServerButton OnClickListener中,如下所示:

findServerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v)
    {
        if(findServerButton.isClickable()) {
            progressDialog.show();
            hostworker = new Settings.HostWorker(); // Line added here.
            hostWorker.execute();
            findServerButton.setClickable(false);
        }
    }
});