本文介绍了无法停止/重启 AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮忙.我可以重新启动 AsyncTask.应用程序每次都崩溃,当第二次调用 updatePoi() 时.

Please help. I can restart the AsyncTask. App crashes every time, when second call to updatePoi().

这是我的代码:

  1. 我正在检查任务状态并设置取消(true).

  1. I'm checking status of task and set cancel(true).

public void updatePoi() {
    //new RefreshMapTask().execute();
    if (refreshMapTask.getStatus() == AsyncTask.Status.RUNNING ||
        refreshMapTask.getStatus() == AsyncTask.Status.PENDING) {
            refreshMapTask.cancel(true);
        }
        refreshMapTask.execute();
    }
}

  • 这是我的 AsyncTask.在 doInBackground 我写了一个休息.

  • Here is my AsyncTask. in doInBackground I wrote a break.

    private class RefreshMapTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            getMapView().getOverlays().clear();
            myPoiOverlay.clear();
            exitOverlay.clear();
        }
    
    
        @Override
        protected Void doInBackground(Void... voids) {
            Application app = (Application)getApplication();
            Log.d(TAG, "exits count = " + app.getExits().size());
    
            GeoPoint pointToNavigate = null;
    
            for (Exit exit : app.getExits()) {
    
                for (Poi poi : exit.getPoi()) {
                    if (isCancelled()){
                        break;
                    }
                    //some code here
                }
            }
    
            //small code here
            return null;
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            getMapView().invalidate();
        }
    }
    

  • 将评论中的解决方案添加到问题中

    added solution from comments into the question

     public void updatePoi() {
    //new RefreshMapTask().execute();
    if (refreshMapTask.getStatus() == AsyncTask.Status.RUNNING ||
        refreshMapTask.getStatus() == AsyncTask.Status.PENDING){
        refreshMapTask.cancel(true);
        refreshMapTask = new RefreshMapTask();
    } else {
        refreshMapTask = new RefreshMapTask();
    }
    refreshMapTask.execute();
    }
    

    推荐答案

    一个 AsyncTask 实例只能被调用一次.要进行第二次调用,您需要创建一个新实例.

    An AsyncTask instance can only be called once. To make a second call, you need to create a new instance.

    这篇关于无法停止/重启 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-30 22:29