我的AsyncTask没有被取消android

时间:2015-12-02 13:34:28

标签: android asynchronous background

我正在处理一个调用AsyncTask的任务,一旦async task被执行,我等待20秒从服务器获取数据,如果它仍在加载我取消它(处理超时)

public void handleServerTimeOut() {
        getStore = new GetStore();
        getStore.execute();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getStore != null && getStore.getStatus() != AsyncTask.Status.FINISHED) {
                    boolean result = getStore.cancel(true);
                    Log.e(TAG, "  handleServerTimeOut() reached 20 seconds");
                    Log.e(TAG, "" + result);
                }
            }
        }, 20000);
    }

的AsyncTask

class GetStore extends AsyncTask<Void, Void, String> {

        String status, message;
        JSONArray jsonArray;
        String buildingIdGuest, buildingIdUser, finalBuildingID;


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            if (isCancelled()) {
                return;
            } else {
                buildingIdUser = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_USER, "");
                buildingIdGuest = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_GUEST, "");
                if (buildingIdUser.equals("0") || buildingIdUser.equals("")) {
                    finalBuildingID = buildingIdGuest;
                } else {
                    finalBuildingID = buildingIdUser;
                }


                error_flag = 0;
                gridView.setVisibility(View.VISIBLE);
                error_layout.setVisibility(View.INVISIBLE);
                img_no_internet.setVisibility(View.INVISIBLE);
                img_no_results.setVisibility(View.INVISIBLE);
                img_server_error.setVisibility(View.INVISIBLE);
                progressDialog.setMessage("Getting nearby stores ...");
                progressDialog.setIndeterminate(true);
                progressDialog.setCancelable(true);
                progressDialog.show();
            }

        }

        @Override
        protected String doInBackground(Void... params) {

            if (NetworkCheck.isNetworkAvailable(getActivity())) {
                try {

                    jsonObj = userFunction.getStores(OS, MAKE, MODEL, finalBuildingID);

                    Log.e(TAG, jsonObj.toString());
                    status = jsonObj.getString("status");
                    message = jsonObj.getString("message");

                    if (status.equalsIgnoreCase("success")) {
                        jsonArray = jsonObj.getJSONArray("response");

                        for (int i = 0; i < jsonArray.length(); i++) {
                            gridModel = new GridModel();
                            gridModel.setId(jsonArray.getJSONObject(i).getString("id"));
                            gridModel.setStore_name(jsonArray.getJSONObject(i).getString("name"));
                            gridModel.setImage_name(jsonArray.getJSONObject(i).getString("image_name"));
                            gridListData.add(gridModel);


                        }
                        Log.e(TAG, "******  =  " + gridListData.toString());

                    } else if (status.equalsIgnoreCase("invalid parameters")) {
                        error_flag = 2;
                        Log.e(TAG, "invalid parameters");
                    } else if (status.equalsIgnoreCase("no stores")) {
                        error_flag = 3;
                        Log.e(TAG, "No Data");
                    }

                    Log.e(TAG, "****** status " + status);
                    return String.valueOf(jsonObj);
                } catch (Exception e) {
                    error_flag = 1; // Handling server timeout.
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();
                            return;
                        }
                    });
                    Log.e(TAG, e.toString());
                }
            } else {
                Log.e(TAG, "Network Error");
                error_flag = 1;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);

            Log.e(TAG, "  **** error **** " + error_flag);

            if (error_flag == 1) {
                gridView.setVisibility(View.GONE);
                error_layout.setVisibility(View.VISIBLE);
                img_no_internet.setVisibility(View.VISIBLE);
            } else if (error_flag == 2) {
                gridView.setVisibility(View.GONE);
                error_layout.setVisibility(View.VISIBLE);
                img_server_error.setVisibility(View.VISIBLE);
                txtError.setVisibility(View.VISIBLE);
                txtError.setText(message);
            } else if (error_flag == 3) {
                gridView.setVisibility(View.GONE);
                error_layout.setVisibility(View.VISIBLE);
                img_no_results.setVisibility(View.VISIBLE);
            }
            gridAdapter = new GridAdapter(getActivity(), gridListData);
            gridView.setAdapter(gridAdapter);
            if ((progressDialog != null) && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }
    }

我还希望在用户取消AsyncTask

时取消ProgressDialog

1 个答案:

答案 0 :(得分:2)

您在isCancelled()方法中仅使用AsyncTask方法检查onPreExecute()一次。当您在任务实例上调用cancel()时,此检查已经过评估,这就是异步任务仍在完成和更新UI的原因。

为了解决这个问题,我建议您使用isCancelled()方法添加更多取消检查。在更新UI之前,在onPostExecute()方法中包含此类检查的一个显而易见的位置。在收到响应之后,您还可以在向服务器发出实际请求之前包括检查等。