【问题标题】:AsyncTask is still running after onPostExecute() in debug window在调试窗口中的 onPostExecute() 之后 AsyncTask 仍在运行
【发布时间】:2012-08-09 12:20:08
【问题描述】:

我有一个创建安卓应用程序的程序。

这个程序的主类使用Async Tasks进行连接,然后请求数据。连接和请求数据都是通过一个按钮启动的,并且在这两种情况下都会显示一个进度条。

当我为 connect 启动 Async Task 时,程序会通过 onPreExecute()、doInBackground()、onProgressUpdate() 和 onPostExecute(),符合预期。

但是在 onPostExecute() 之后,当我查看调试器窗口时,AsyncTask 仍在运行并继续运行。然后当我请求数据时,会创建一个新的 AsyncTask 并且我有两个正在运行。

如何终止第一个 AsyncTask(实际上是第二个完成后),因为在使用该程序一段时间后,我最终得到了大约 20 个 AsyncTask 线程还在运行!

我在下面包含了我的代码:

private ProgressDialog connectionDialog;
private ProgressDialog requestDataDialog;

private ProgressDialog usingDialog;

private int currentDialog;

public void connectClick(View view) //When the connect button is clicked
{
    currentDialog = 1;

    new PerformTask().execute();
}

private class PerformTask extends AsyncTask<Void, Integer, Integer> 
{
    protected void onPreExecute()
    {
        showDialog(currentDialog);
    }

    protected Integer doInBackground(Void... voi) 
    {
        int total = 0;

        //Perform the task required

        publishProgress(total);

        return total;
    }

    protected void onProgressUpdate(Integer... progress) 
    {
        usingDialog.setProgress(progress[0]);
    }

    protected void onPostExecute(Integer result) 
    {
        removeDialog(currentDialog);
    }
}

protected Dialog onCreateDialog(int id) 
{   
    //Setup the dialogs
}

public void requestDownloadClick(View view)
{
    currentDialog = 2;

    new PerformTask().execute();
}

【问题讨论】:

  • 你用的是什么安卓版本?从 Honeycomb 开始,所有异步任务都在单个线程上运行。您也可以使用 threadpoolExecutor,然后使用 Asynctasks.executeonExecutor developer.android.com/reference/android/os/AsyncTask.html
  • stackoverflow.com/a/3077508/1514187 检查这个答案。
  • 好吧,基本上 - 没关系,反正我也无能为力。谢谢。我确实尝试搜索类似的问题,但没有找到。

标签: java android android-asynctask terminate


【解决方案1】:

为了完整起见,我可以接受这个问题,这里是 grv_9098 给出的答案,在 stackoverflow.com/a/3077508/1514187 上找到:

AsyncTask 管理一个使用 ThreadPoolExecutor 创建的线程池。它将有 5 到 128 个线程。如果线程数超过 5 个,则这些多余的线程最多会停留 10 秒,然后才会被移除。 (注意:这些数字是针对目前可见的开源代码,因 Android 版本而异)。

请不要管 AsyncTask 线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多