简体   繁体   English

具有asynctask的Android活动生命周期

[英]Android activity life cycle with asynctask

I have been doing some research on activity life cycles and how they free usable space so my application can run smoother. 我一直在研究活动的生命周期,以及它们如何释放可用空间,以便我的应用程序可以更流畅地运行。 Its just that I would like to use these methods for one of my activities because when my PDialog launches it takes quite some time for my data to load. 只是我想对这些活动之一使用这些方法,因为当我启动PDialog时,要花很多时间才能加载数据。 I have been look at my code to see where I can place these method, so when my activity is executing my asynctask, That will be the only thing I want to be running at that point of time.my code below will clear things up. 我一直在看我的代码以查看可以在何处放置这些方法,因此,当我的活动正在执行asynctask时,那将是我当时想要运行的唯一操作。下面的代码将清除所有问题。

    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";

                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> {


            private Dialog pDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                ProgressDialog pDialog; 
                pDialog = new ProgressDialog(ListView.this);
                pDialog.setMessage("Loading Data. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                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 NumAnswers = question.getString(TAG_QUESTION_NUMANSWERS);
                        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_NUMANSWERS, NumAnswers);
                                   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, TAG_QUESTION_NUMANSWERS }, new int[] {
                            R.id.Subject, R.id.NumAnswers, });

                    setListAdapter(adapter); 


            }

        }

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

    }

In my previous class I have already put onStop to free up some space. 在上一堂课中,我已经放了onStop来释放一些空间。 But I hope now you can see more of what I mean when I say that I just want to PDialog and my asynctask to be running at that point of time so that my PDialog doesn't slow down the process. 但是我希望现在您能看到更多我的意思,当我说我只是想让PDialog和asynctask在那个时间点运行时,以便我的PDialog不会减慢该过程。

For me is not actually clear what is question about. 对我来说,实际上并不清楚要问什么。 For a reference two important points if some newbee comes here and read. 作为参考,如果有一些新蜜蜂来这里阅读,请注意两个要点。

  1. it takes some time list to load because it is long operation. 由于操作时间长,因此需要一些时间来加载。 Purpose of AsyncTask is to keep UI not blocked . AsyncTask的目的是保持UI不受阻塞 It's purpose is not to magicaly speed up things to infinity (btw even if it is light speed is a limit). 目的不是要神奇地将事物加速到无限(顺便说一句,即使光速是极限)。
  2. onStop() in this code is useless, it does nothing. 此代码中的onStop()是无用的,它什么也不做。 super.onStop() would be called even if you delete completely your overriden onStop method because base class ListActivity is extended from Activity which has this method and it will be called. 即使您完全删除覆盖的onStop方法,也会调用super.onStop()因为基类ListActivity是从具有此方法的Activity扩展的,并且将被调用。 You didn't add anything by just calling super.onStop() 您仅通过调用super.onStop()并没有添加任何内容
  3. Just for records onPreExecuting and onPostExecute are executing on main (UI) thread.. doInBackground is running in separate thread but Android wrapped everything nice for you so these methods execute on appropriate threads one after another. 仅针对onPreExecutingonPostExecute记录在主(UI)线程上执行doInBackground在单独的线程中运行,但是Android打包了所有对您doInBackground东西,因此这些方法在适当的线程上doInBackground执行。
  4. Seems like you don't know why but your doInBackground method needed to return some string so you returned any that you had ( TAG_QUESTION ).. ;) than onPostExecute accepted that String as parameter but of course you didn't use it. 似乎您不知道为什么,但是您的doInBackground方法需要返回一些字符串,因此您返回了所拥有的任何内容( TAG_QUESTION ..;;),而不是onPostExecute接受了String作为参数,但是您当然没有使用它。 String was required there because you declared AsyncTask with <String,String,String> not knowning what is that for. 在那里需要<String,String,String>因为您用<String,String,String>声明了AsyncTask而不知道它是干什么的。

Hopefully some material about AsyncTask class can help to someone who landed here 希望一些有关AsyncTask类的材料可以对登陆这里的人有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM