简体   繁体   English

AsyncTask 不会停止

[英]AsyncTask doesn't stop

I've created an AsyncTask that loads messaging history from a database and then shows it on the device screen:我创建了一个 AsyncTask,它从数据库中加载消息历史,然后将其显示在设备屏幕上:

private void loadHistoryFromDB(Date lastUpdateDate)
    {
    final class DBAsyncTask extends AsyncTask<Void, Void, List<XMPPMessage>>
    {
        @Override
        protected List<XMPPMessage> doInBackground(Void... arg0) 
        {
            List<XMPPMessage> messages = null;
            try 
            {
                messages = PersistenceManager.getXMPPMessagesFromDB(userInfo, 0, messagingActivity);
            }
            catch (SQLException e) 
            {
                e.printStackTrace();
            } 
            catch (LetsDatabaseException e)
            {
                e.printStackTrace();
            }
            return messages;
        }

It seems to work fine, but after being executed, it leaves 2 running threads and I can't finish the activity because of that.它似乎工作正常,但在执行后,它留下了 2 个正在运行的线程,因此我无法完成活动。 How can I fix it?我该如何解决?

As long as your tasks are executing properly (exits from onPostExecute ), this shouldn't be something you have to worry about.只要您的任务正确执行(从onPostExecute退出),您就不必担心。 Once executed, AsyncTask thread(s) will stick around for possible reuse in the form of a thread pool or single thread, depending on platform version.一旦执行, AsyncTask线程将继续存在,以便以线程池或单线程的形式重复使用,具体取决于平台版本。 This is normal behaviour - they will eventually be cleaned-up/reused.这是正常行为 - 它们最终将被清理/重用。

This problem is most likely due to confusion surrounding the cancel method of AsyncTask.这个问题很可能是由于对 AsyncTask 的取消方法的混淆造成的。

You need to break down your background task into loopable segments, then Before each loop iteration starts doing your task,you need to check if the task is cancelled and if it is you need to break the loop.您需要将后台任务分解为可循环的段,然后在每次循环迭代开始执行任务之前,您需要检查任务是否被取消以及是否需要中断循环。 There doesn't seem to be any other way to stop an AsyncTask from executing.似乎没有其他方法可以阻止 AsyncTask 执行。

I've posted a detailed guide to this problem with code examples here:我已在此处通过代码示例发布了有关此问题的详细指南:

http://tpbapp.com/android-development/android-asynctask-stop-running-cancel-method/ http://tpbapp.com/android-development/android-asynctask-stop-running-cancel-method/

First off, make sure you are calling super.doInBackGround() at the top of your overridden method call.首先,确保您在重写方法调用的顶部调用super.doInBackGround()

If that isn't it, it's likely because you are maintaining the connecting to the database.如果不是这样,很可能是因为您正在维护与数据库的连接。

That is, you still have a lock established on the database.也就是说,您仍然在数据库上建立了锁。

See if you can explicitly unlock the database, that may fix your problem.看看您是否可以显式解锁数据库,这可能会解决您的问题。

You could put it in the onPostExecute() method.你可以把它放在onPostExecute()方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM