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

前端 未结 4 1978
轻奢々
轻奢々 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: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 {
    
        @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
    {
        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  mytest = new testtask().execute(new MyGenericMethod() {
            public int execute(String param) {
                //body
                return 1;
            }
        });     
    }
    

提交回复
热议问题