使用android后退按钮和Progressdialog取消AsyncTask

时间:2013-08-25 04:04:58

标签: android android-asynctask

我有一个在我的asynctask中运行的进度对话框,当asynctask需要一段时间加载时,我希望用户能够按下Android设备上的后面以停止asynctask完成。我已经做了我自己的研究,看看我是否可以自己做,但我已经被你可以使用的不同方法所淹没。我已经看了一些关于stackoverflow的问题但是每个人都有不同并使用不同的方法。所以我只是希望有人可以帮助我并告诉我我的具体情况需要做些什么。我也很乐意阅读教程。

public class ListView extends ListActivity {    


    ArrayList<HashMap<String, String>> questionList;        

     final String TAG_RESULTS = "results";
     final String TAG_QUESTION_SUBJECT = "Subject";
     final String TAG_QUESTION_NUMANSWERS = "NumAnswers";
     final String TAG_QUESTION = "question";
     final String TAG_QUESTION_CONTENT = "Content";
     final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
     final String TAG_ANSWERS = "Answers";
     final String TAG_ANSWER = "Answer";    
     final String TAG_ANSWERS_CONTENT = "content";      
     final String TAG_QUERY = "query";
     ProgressDialog pDialog;

            JSONArray question = null;          
            android.widget.ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        //setContentView(R.layout.listview);        

    questionList = new ArrayList<HashMap<String, String>>(); 


    new LoadAllData().execute();

        }


    @Override   
    protected void onListItemClick(android.widget.ListView l, View v, int pos, long id) {
         super.onListItemClick(l, v, pos, id);  

          HashMap<String, String> item = questionList.get(pos);

          Intent i = new Intent(ListView.this, SingleListItem.class);
          i.putExtra(TAG_QUESTION_SUBJECT, item.get(TAG_QUESTION_SUBJECT));
          i.putExtra(TAG_QUESTION_CONTENT, item.get(TAG_QUESTION_CONTENT));
          i.putExtra(TAG_QUESTION_CHOSENANSWER, item.get(TAG_QUESTION_CHOSENANSWER));
          startActivity(i);

            }     

    class LoadAllData extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();             
            pDialog = new ProgressDialog(ListView.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            try {
                Intent in = getIntent();
                String searchTerm = in.getStringExtra("TAG_SEARCH");
                String query = URLEncoder.encode(searchTerm, "utf-8");
                String URL = "http://example.com";
                JSONParsser jParser = new JSONParsser();
                JSONObject json = jParser.readJSONFeed(URL);
                try {

                    JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

                    for(int i = 0; i < questions.length(); i++) {
                        JSONObject question = questions.getJSONObject(i);


                    String Subject = question.getString(TAG_QUESTION_SUBJECT);
                    String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
                    String Content = question.getString(TAG_QUESTION_CONTENT);

                    //JSONArray Answers = question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);


                    //JSONObject Answer = Answers.getJSONObject(0);

                    //String Content = Answer.getString(TAG_ANSWERS_CONTENT);

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

                               map.put(TAG_QUESTION_SUBJECT, Subject);
                               map.put(TAG_QUESTION_CONTENT, Content);
                               map.put(TAG_QUESTION_CHOSENANSWER, ChosenAnswer);

                               questionList.add(map);

                    }


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

                return TAG_QUESTION ;           

        }

        @Override
        protected void onPostExecute(String file_URL) {
            if (pDialog != null && pDialog.isShowing()) pDialog.dismiss();
            ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
                        R.layout.listelements,
                        new String[] { TAG_QUESTION_SUBJECT }, new int[] {
                        R.id.Subject,});

                setListAdapter(adapter);                

        }       
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }   
}

1 个答案:

答案 0 :(得分:0)

像这样使用。

1)取消Asynctask

@Override
public void onBackPressed() 
{              
    /** If user Pressed BackButton While Running Asynctask
        this will close the ASynctask.
     */
    if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
    {
        mTask.cancel(true);
    }          
    super.onBackPressed();
}


@Override
protected void onDestroy() {
    // TODO Auto-generated method stub


/** If Activity is Destroyed While Running Asynctask
        this will close the ASynctask.   */

 if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
 {
    mTask.cancel(true);
  }  

    super.onDestroy();

}

2)取消ProgressDialog

@Override
protected void onPause() {
    // TODO Auto-generated method stub


 if (mProgressDialog != null)
 {
     if(mProgressDialog.isShowing())
     {
         mProgressDialog.dismiss();
     }
        super.onPause();

  }  

}

编辑:以这种方式使用Asynctask 将Asynctask声明为全局变量

 LoadAllData mTask;

&安培;在onCreate(..)

中初始化
mTask=new LoadAllData(YourActivity.this);

&安培;执行

mTask.execute("yourString");