取消AsyncTask不带循环

时间:2015-10-06 11:52:12

标签: java android android-asynctask

我想取消Android应用程序中的AsyncTask。踢球者是,我的AsyncTask不包含循环,所以我不能使用break。

这是我的AsyncTask.doInBackground():

protected Void doInBackground(String... params) {
            String location = params[1];
            if(!location.matches("-?[0-9.]*,-?[0-9.]*")) {
                try {
                    location = Util.getLatLngFromMapsQuery(location);
                } catch (UnchainedAPIException e) {
                    setErrorCode(ERROR_GEO);
                    this.cancel(true);
                }
            }
            UnchainedAPI unchainedAPI = new UnchainedAPI(YELP_KEY, YELP_SECRET, YELP_TOKEN, YELP_TOKEN_SECRET,
                    FOURSQUARE_ID, FOURSQUARE_SECRET, GOOGLE_PLACES_KEY);
            try {
                nonChains = unchainedAPI.getUnchainedRestaurants(params[0], location);
            } catch (UnchainedAPIException e) {
                setErrorCode(ERROR_API);
                this.cancel(true);
            }

            if(nonChains.size() == 0) {
                setErrorCode(ERROR_API);
            }
            return null;
        }

我可以在这做什么?

2 个答案:

答案 0 :(得分:2)

AsyncTask.cancel(boolean mayInterruptIfRunning) 

诀窍。

或从任务内部开始:

cancel(true);

答案 1 :(得分:1)

如果你需要从doInBackground()中断AsyncTask,只需使用

return null;

你需要打破的地方。从onPostExecute()可以使用

this.cancel(true);