如果某些条件为真,如何停止AsyncTask

时间:2013-09-18 09:10:41

标签: android android-asynctask

我使用asynctask从远程url获取json数据,但有时这个url会在json数据中返回错误,如下所示:

{
   "error": {
      "message": "(#803) Some of the aliases you requested do not exist: RNN.NES",
      "type": "OAuthException",
      "code": 803
   }
}

在doInBackground中,我检查json是否有错误..

if(true) {
    //cancel asynctask and show toast with message i use 
    cancel(true)
}

但我这样做,条件是真的,但没有取消

这是我的代码:

private class MyAsyncTask extends AsyncTask<String, Void, Void> {

        ProgressDialog mProgressDialog;

        @Override
        protected void onPostExecute(Void result) {
            db = new DAOPages(context);
            db.open();
            db.addPage(name, fid, picName);
            getPagePrefs(fid);
            db.close();
            mProgressDialog.dismiss();

            Intent intent = new Intent(context, PagePrefsActivity.class);
            intent.putExtra("fPageid", fid);
            context.startActivity(intent);

        }

        @Override
        protected void onPreExecute() {

            mProgressDialog = ProgressDialog.show(context, "Loading...",
                    "Data is Loading...");
        }

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

            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(params[0]);
            // addPageData(params[0]);
            try {

                if(json.getJSONObject("error") != null) {
                    Log.e("error", "true");
                    cancel(true);
                }
                name = json.getString("name");
                fid = json.getString("id");                                 

                String picture = json.getJSONObject("picture")
                        .getJSONObject("data").getString("url");
                picName = downloadImage(picture, fid);

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

现在我怎么能阻止它并显示吐司?

提前致谢

2 个答案:

答案 0 :(得分:1)

方法cancel(true)不会停止AsyncTask。在doInBackGround返回后,它只调用onCancelled()而不是onPostExecute()。您可以使用AsyncTask.isCancelled(),如果取消AsyncTask,它将返回true,以防止在doInBackground()中进一步处理。

所以重写onCancelled()并将你的Toast放在那里。

private class MyAsyncTask extends AsyncTask<String, Void, Void> {

        ProgressDialog mProgressDialog;

        @Override
        protected void onPostExecute(Void result) {
            db = new DAOPages(context);
            db.open();
            db.addPage(name, fid, picName);
            getPagePrefs(fid);
            db.close();
            mProgressDialog.dismiss();

            Intent intent = new Intent(context, PagePrefsActivity.class);
            intent.putExtra("fPageid", fid);
            context.startActivity(intent);

        }

        @Override
        protected void onPreExecute() {

            mProgressDialog = ProgressDialog.show(context, "Loading...",
                    "Data is Loading...");
        }

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

            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(params[0]);
            // addPageData(params[0]);
            try {

                if(json.getJSONObject("error") != null) {
                    Log.e("error", "true");
                    cancel(true); // after this AsyncTask.isCancelled() returns true
                }

                if(!this.isCancelled()){ // if it's true, prevent further processing
                     name = json.getString("name");
                     fid = json.getString("id");                                 

                     String picture = json.getJSONObject("picture")
                            .getJSONObject("data").getString("url");
                     picName = downloadImage(picture, fid);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        // will be called instead onPostExecute after a cancel
        @Override
        protected void onCancelled() {
            // Show your Toast 
        }
    }

答案 1 :(得分:0)

您可以在onPostExecute()方法中使用isCancelled()进行检查,并可以在该方法中显示Toast。这是您可以这样做的方式 - :

    @Override
    protected void onPostExecute(Void result) {
        if(isCancelled()) {
            Toast.makeText(context, "your text", Toast.LENGTH_SHORT).show();
            return;
        }
        db = new DAOPages(context);
        db.open();
        db.addPage(name, fid, picName);
        getPagePrefs(fid);
        db.close();
        mProgressDialog.dismiss();

        Intent intent = new Intent(context, PagePrefsActivity.class);
        intent.putExtra("fPageid", fid);
        context.startActivity(intent);

    }