What arguments are passed into AsyncTask?

后端 未结 5 1779
陌清茗
陌清茗 2020-11-22 16:49

I don\'t understand what I am supposed to put in here and where these arguments end up? What exactly should I put, and where exactly will it go? Do I need to include all 3 o

5条回答
  •  忘了有多久
    2020-11-22 17:31

    Keep it simple!

    An AsyncTask is background task which runs in the background thread. It takes an Input, performs Progress and gives Output.

    ie AsyncTask.

    In my opinion the main source of confusion comes when we try to memorize the parameters in the AsyncTask.
    The key is Don't memorize.
    If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.
    Just figure out what your Input, Progress and Output are and you will be good to go.

    For example:

    Heart of the AsyncTask!

    doInBackgound() method is the most important method in an AsyncTask because

    • Only this method runs in the background thread and publish data to UI thread.
    • Its signature changes with the AsyncTask parameters.

    So lets see the relationship

    doInBackground() and onPostExecute(),onProgressUpdate() are also related

    Show me the code
    So how will I write the code for DownloadTask?

    DownloadTask extends AsyncTask{
    
          @Override
          public void onPreExecute()
          {}
    
          @Override
          public String doInbackGround(String... params)
          {
                   // Download code
                   int downloadPerc = // calculate that
                   publish(downloadPerc);
    
                   return "Download Success";
          }
    
          @Override
          public void onPostExecute(String result)
          {
              super.onPostExecute(result);
          }
    
          @Override
          public void onProgressUpdate(Integer... params)
          {
                 // show in spinner, access UI elements
          }
    
    }
    

    How will you run this Task

    new DownLoadTask().execute("Paradise.mp3");
    

提交回复
热议问题