簡體   English   中英

如何停止asyncTask android

[英]how to stop asyncTask android

在我的Android項目中,我在一項活動中使用了許多AsynTask 啟動其他AsynTask時,我需要停止其中一個。

我正在使用myAsynTask.cancel(true); 在我的android項目中。 但是它確實停止了AsynTask

protected String doInBackground(String... args) {

        HashMap<String, String> params = new HashMap<>();
        params.put("id", args[0]);

        Log.d("get value: ", params.toString());

        JSONObject json = jParser.makeHttpRequest(url_comment, "GET", params);

        Log.d("All matches: ", json.toString());

        if(isCancelled()) {
            finish();
        }
        else {

            try {

                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {

                    JSONmatches = json.getJSONArray(TAG_vedio);

                    for (int i = 0; i < JSONmatches.length(); i++) {
                        JSONObject c = JSONmatches.getJSONObject(i);

                        String title = c.getString(TAG_title);
                        String url = c.getString(TAG_url);

                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put(TAG_title, title);
                        map.put(TAG_url, url);

                        arrayList22.add(map);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

您積極把檢查isCancelled在執行在循環doInBackground

如果isCanceled為true,則應該break循環。

從官方的Android文檔中

可以通過調用cancel(boolean)任務。 調用此方法將導致對isCancelled()后續調用返回true。 調用此方法后,在doInBackground(Object[])返回之后,將調用onPostExecute(Object)而不是onPostExecute(Object) 為了確保盡快取消任務,如果可能的話(例如在循環內doInBackground(Object[]) ,應始終定期從doInBackground(Object[])檢查isCancelled()的返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM