Can somebody explain how to use ASyncTask with Android?

后端 未结 4 1139
生来不讨喜
生来不讨喜 2021-01-16 07:13

I\'ve been doing a bunch of research and looking over the documentation for ASyncTask in Android, but I just can\'t seem to wrap my head around it. I simply want to run some

4条回答
  •  既然无缘
    2021-01-16 07:49

    AsyncTask uses parameterized types (java generics) so that you can specify the types it uses when you define your own AsyncTask. Perhaps it's easier to explain in this form:

    public abstract class AsyncTask {
        ...
        protected abstract Result doInBackground(Params... params);
    
        protected abstract void onProgressUpdate(Progress... progress);
    
        protected abstract void onPostExecute(Result result);
        ...
    }
    

    There are no classes named Params, Progress, or Result. These are instead generic types. They are just placeholders for types you wish to use when you define your own AsyncTask subclass. The above could equally be written as such:

    public abstract class AsyncTask {
        ...
        protected abstract C doInBackground(A... params);
    
        protected abstract void onProgressUpdate(B... progress);
    
        protected abstract void onPostExecute(C result);
        ...
    }
    

    Suppose I were defining an AsyncTask that takes a list of Strings representing URLs, and it will ping each one to see if it's reachable, then return the number that were reachable. Meanwhile, with each test, it will update a ProgressBar as each test completes. It might look something like this:

    public class MyAsyncTask extends AsyncTask {
    
        @Override
        protected Integer doInBackground(String... params) {
            int total = params.length;
            int successfulPings = 0;
            for (int i = 0; i < total; i++) {
                if (isReachable(params[i])) {
                    successfulPings++;
                }
                publishProgress(i, total);
            }
            return successfulPings;
        }
    
        @Override
        protected void onProgressUpdate(Integer... progress) {
            int testsSoFar = progress[0];
            int totalTests = progress[1];
            progressBar.setMax(totalTests);
            progressBar.setProgress(testSoFar);
        }
    
        @Override    
        protected void onPostExecute(Integer result) {
            Toast.makeTest(context, "Reached " + result + " sites.", Toast.LENGTH_SHORT).show();
        }
    }
    

    I would initiate this as follows:

    String[] urls = ...
    MyAsyncTask task = new MyAsyncTask();
    task.execute(urls);
    

    The argument passed into execute will be passed into doInBackground. Whatever you do in doInBackground, you need to return something that gets passed in as the argument to onPostExecute. While in doInBackground, you can call publishProgress, where you can do something like I did (but you don't have to).

提交回复
热议问题