如何取消异步任务并显示Toast消息

时间:2014-10-01 07:16:28

标签: android android-asynctask

我从服务中收到了json数据。我使用asynctask来获取数据。当数据为空时,我想取消asynstask并向用户显示一些消息。

        public class MainActivity extends ActionBarActivity {

            // Progress Dialog
            private ProgressDialog pDialog;

            private LoadCategories mTask;

    .....

     /**
             * Listening to Load More button click event
             * */
            btnLoadMore.setOnClickListener(new View.OnClickListener() { 
                @Override
                public void onClick(View arg0) {                
                    if (URL_CATEGORY == null || URL_CATEGORY == "")
                    {Toast.makeText(MainActivity.this,"URL est vide", Toast.LENGTH_LONG).show();}
                    else
                    { // Starting a new async task
                        //new LoadCategories().execute();
                        mTask = new LoadCategories();
                        mTask.execute();
                        }               
                }
            });

    ....

     class LoadCategories extends AsyncTask<String, String, String> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("en cours...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);

                pDialog.show();
            }

            @Override
            protected String doInBackground(String... args) {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();

                // getting JSON string from URL
                String json = jsonParser.makeHttpRequest(URL_CATEGORY, "GET",
                        params); 

                if (json == null || json == "")
                {
                    mTask.cancel(true);
    //               if(isCancelled())
    //               {Toast.makeText(MainActivity.this,"Donée sont vide", Toast.LENGTH_LONG).show();}
                    synchronized(this) {
                        while (json.length() == 0) {
                            if(mTask.isCancelled()) 
                            { Toast.makeText(MainActivity.this,"Donée sont vide", Toast.LENGTH_LONG).show();}                      
                        }
                    }   
                }
                // Check your log cat for JSON reponse
                Log.d("Categories JSON: ", "> " + json);  
                return json;
            }

            @Override
            protected void onPostExecute(String json) {
                try {
                    categories = new JSONArray(json);
                    categoryList.clear();
                    if (categories != null) {
                        // looping through All albums
                        for (int i = 0; i < categories.length(); i++) {
                            JSONObject c = categories.getJSONObject(i);
.....

我的问题是程序永远不会取消并显示消息。 当我调试它时,它进入我的状态

if (json == null || json == "")
            {
                mTask.cancel(true);
//               if(isCancelled())
//               {Toast.makeText(MainActivity.this,"Donée sont vide", Toast.LENGTH_LONG).show();}
                synchronized(this) {
                    while (json.length() == 0) {
                        if(mTask.isCancelled()) 
                        { Toast.makeText(MainActivity.this,"Donée sont vide", Toast.LENGTH_LONG).show();}                      
                    }
                }   
            }

4 个答案:

答案 0 :(得分:1)

试试这个......

    protected String doInBackground(String... args) {
        // code
        if (json.equals(null) || json.equals("")){
            if(mTask.isCancelled()) break;
            return null;
        }

       return json;
    }

onPostExecute

   protected void onPostExecute(String json) {
     if(json.equals(null) || json.equals("")){
         // Make a toast Message
     }else{
        // your code
     }

无需取消您的异步任务....

答案 1 :(得分:0)

只需在异步类后台检查isCancelled()一次:

 protected String doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }

答案 2 :(得分:0)

从Android文档中,您可以覆盖在取消AsyncTask时将调用的onCancelled()方法

  

取消任务
  可以通过调用随时取消任务   取消(布尔值)。调用此方法将导致后续调用   isCancelled()返回true。调用此方法后,   onCancelled(Object),而不是onPostExecute(Object)将被调用   在doInBackground(Object [])返回之后。确保完成任务   尽快取消,你应该经常检查退货   ifCancelled()的值定期来自doInBackground(Object []),if   可能的(例如在循环内)。

或者您也可以在循环中检查isCancelled,例如:

if (isCancelled()) {
    Toast.makeText(getContext(), "AsyncTask is Cancelled", Toast.LENGTH_SHORT).show();
    break;
}
else
{
   // some process
}

答案 3 :(得分:0)

如果您要处理取消活动,请覆盖onCancelled()课程中AsyncTask的{​​{1}}方法。将用于显示toast消息的代码移动到您自己的LoadCategories方法中。

但是,我认为onCancelled()没有必要。我建议检查mTask.cancel()值并决定在json中显示Toast消息。

相关问题