Android: How can I pass parameters to AsyncTask's onPreExecute()?

前端 未结 4 1852
轻奢々
轻奢々 2020-12-02 04:32

I use an AsyncTask for loading operations that I implemented as an inner class.

In onPreExecute() I show a loading dialog which I then hid

相关标签:
4条回答
  • 2020-12-02 05:01

    You can either pass the parameter in the task constructor or when you call execute:

    AsyncTask<Object, Void, MyTaskResult>
    

    The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).

    public class MyActivity extends AppCompatActivity {
    
        TextView textView1;
        TextView textView2;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);    
            textView1 = (TextView) findViewById(R.id.textView1);
            textView2 = (TextView) findViewById(R.id.textView2);
    
            String input1 = "test";
            boolean input2 = true;
            int input3 = 100;
            long input4 = 100000000;
    
            new MyTask(input3, input4).execute(input1, input2);
        }
    
        private class MyTaskResult {
            String text1;
            String text2;
        }
    
        private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
            private String val1;
            private boolean val2;
            private int val3;
            private long val4;
    
    
            public MyTask(int in3, long in4) {
                this.val3 = in3;
                this.val4 = in4;
    
                // Do something ...
            }
    
            protected void onPreExecute() {
                // Do something ...
            }
    
            @Override
            protected MyTaskResult doInBackground(Object... params) {
                MyTaskResult res = new MyTaskResult();
                val1 = (String) params[0];
                val2 = (boolean) params[1];
    
                //Do some lengthy operation    
                res.text1 = RunProc1(val1);
                res.text2 = RunProc2(val2);
    
                return res;
            }
    
            @Override
            protected void onPostExecute(MyTaskResult res) {
                textView1.setText(res.text1);
                textView2.setText(res.text2);
    
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-02 05:10

    You can override the constructor. Something like:

    private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
    
        public MyAsyncTask(boolean showLoading) {
            super();
            // do stuff
        }
    
        // doInBackground() et al.
    }
    

    Then, when calling the task, do something like:

    new MyAsyncTask(true).execute(maybe_other_params);
    

    Edit: this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:

    MyAsyncTask task = new MyAsyncTask();
    task.showLoading = false;
    task.execute();
    
    0 讨论(0)
  • 2020-12-02 05:15

    1) For me that's the most simple way passing parameters to async task is like this

    // To call the async task do it like this
    Boolean[] myTaskParams = { true, true, true };
    myAsyncTask = new myAsyncTask ().execute(myTaskParams);
    

    Declare and use the async task like here

    private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
    
        @Override
        protected Void doInBackground(Boolean...pParams) 
        {
            Boolean param1, param2, param3;
    
            //
    
              param1=pParams[0];    
              param2=pParams[1];
              param3=pParams[2];    
          ....
    }                           
    

    2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.

     /* Generic Async Task    */
    interface MyGenericMethod {
        int execute(String param);
    }
    
    protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
    {
        public String mParam;                           // member variable to parameterize the function
        @Override
        protected Void doInBackground(MyGenericMethod... params) {
            //  do something here
            params[0].execute("Myparameter");
            return null;
        }       
    }
    
    // to start the asynctask do something like that
    public void startAsyncTask()
    {
        // 
        AsyncTask<MyGenericMethod, Void, Void>  mytest = new testtask().execute(new MyGenericMethod() {
            public int execute(String param) {
                //body
                return 1;
            }
        });     
    }
    
    0 讨论(0)
  • 2020-12-02 05:23

    why, how and which parameters are passed to Asynctask<>, see detail here. I think it is the best explanation.

    Google's Android Documentation Says that :

    An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

    AsyncTask's generic types :

    The three types used by an asynchronous task are the following:

    Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

     private class MyTask extends AsyncTask<Void, Void, Void> { ... }
    

    You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html

    Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog

    Well The structure of a typical AsyncTask class goes like :

    private class MyTask extends AsyncTask<X, Y, Z>
    
        protected void onPreExecute(){ 
    
        } 
    

    This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.

    protected Z doInBackground(X...x){
    
    }
    

    The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.

    protected void onProgressUpdate(Y y){

    } This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.

    protected void onPostExecute(Z z){

    } This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.

    What about the X, Y and Z types?

    As you can deduce from the above structure:

    X – The type of the input variables value you want to set to the background process. This can be an array of objects.
    
     Y – The type of the objects you are going to enter in the onProgressUpdate method.
    
     Z – The type of the result from the operations you have done in the background process.
    

    How do we call this task from an outside class? Just with the following two lines:

    MyTask myTask = new MyTask();
    
    myTask.execute(x);
    

    Where x is the input parameter of the type X.

    Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.

    myTask.getStatus(); and we can receive the following status:

    RUNNING - Indicates that the task is running.

    PENDING - Indicates that the task has not been executed yet.

    FINISHED - Indicates that onPostExecute(Z) has finished.

    Hints about using AsyncTask

    Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.

    You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.

    The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).

    The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

    0 讨论(0)
提交回复
热议问题